पाठ 23 / 26
xUnit से Testing
Unit tests और WebApplicationFactory से in-memory integration test लिखें।
दो तरह के tests
Unit tests एक class को उसकी dependencies के नकली objects के साथ जाँचते हैं और milliseconds में चलते हैं। Integration tests WebApplicationFactory<Program> से असली ऐप pipeline memory में चलाकर उसे HTTP requests भेजते हैं। पहले वाले ज़्यादा और दूसरे कम रखें।
एक unit test और एक API test
Test project को दिखाने के लिए Program.cs के अंत में public partial class Program { } जोड़ें। सब कुछ dotnet test से चलाएँ।
public class GreeterTests
{
[Fact]
public void Greet_ReturnsGreeting()
=> Assert.Equal("Hello, Asha!", new Greeter().Greet("Asha"));
}
public class ApiTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task Root_ReturnsOk()
{
var res = await factory.CreateClient().GetAsync("/");
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
}
}Wiring नहीं, व्यवहार test करें
जो tests implementation को पंक्ति-दर-पंक्ति दोहराते हैं वे हर refactor पर टूटते हैं। ऐसे नतीजों पर assert करें जो caller देख सके: status codes, response bodies और saved data।
त्वरित जाँच: WebApplicationFactory<Program> क्या देता है?
- आपके ऐप को चलाता in-memory test server
- Production load balancer
- Database schema generator
- Code formatter
Answer
आपके ऐप को चलाता in-memory test server — यह आपकी असली pipeline को test process में चलाता है ताकि आप उसे `HttpClient` से बुला सकें।