网络核心:集成测试中的依赖注入

时间:2019-07-31 08:26:48

标签: c# asp.net-core .net-core xunit

如何在集成测试中进行依赖注入? 呼叫departmentRepositorydepartmentAppService给我null,并在下面显示错误。

public class DepartmentAppServiceTest
{
    public SharedServicesContext context;
    public IMapper mapper;
    public IRepository<Department, int> departmentRepository;
    public IDepartmentAppService departmentAppService;

    public DepartmentAppServiceTest()
    {
        ServiceCollection services = new ServiceCollection();
        services.AddTransient<IRepository<Department>, BaseRepository<Department>>();
        services.AddTransient<IDepartmentAppService, DepartmentAppService>();
分别调用此存储库或应用程序服务的

调试和设置断点为空

新方法

 [Fact]
 var departmentDto = await departmentAppService.GetDepartmentById(2);

应用服务的构造者

DepartmentAppService(departmentRepository, mapper)
DepartmentRepository(dbcontext)

错误:

  

消息:System.NullReferenceException:对象引用未设置为   对象的实例。

3 个答案:

答案 0 :(得分:0)

使用Moq,您将能够伪造违规行为,然后将其传递给您的服务。例如,您的测试方法可能类似于:

//arrange  
var company = new company() { company_name = "TCS" };  

var mockRepo = new Mock<ICompany>();  
mockRepo.Setup(x => x.InsertCompany(company)).Returns(true);  

var companyObject = new Company(mockRepo.Object);  
var retrnData = companyObject.InsertCompany(company)

此代码段摘自本文,我建议您检查一下:

https://www.c-sharpcorner.com/UploadFile/dacca2/unit-test-using-mock-object-in-dependency-injection/

答案 1 :(得分:0)

如果使用departmentAppService局部变量,则为null。您的对象在容器中。您可以通过调用GetRequiredService或GetService方法来检索它。

我以这种方式在控制台应用程序中使用了ServiceCollection。

IServiceCollection services = new ServiceCollection();

services.AddSingleton<IDepartmentAppService, DepartmentAppService>();

using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
  var departmentAppService = serviceProvider.GetRequiredService<IDepartmentAppService>();

  await departmentAppService.GetDepartmentById(2);
}

需要注意的是,正在为每个测试用例重新创建测试类。

答案 2 :(得分:0)

对于我们的集成测试,我们以编程方式启动应用程序,并使用HttpClient对API端点进行调用。通过这种方式,您的应用程序可以在整个启动过程中运行,并且依赖项注入就像一个魅力一样。

以下是服务器启动和客户端创建的示例,可以将它们重新用于多个测试:

_server = new TestServer(new WebHostBuilder()
                .UseEnvironment("Testing")
                .UseContentRoot(applicationPath)
                .UseConfiguration(new ConfigurationBuilder()
                    .SetBasePath(applicationPath)
                    .AddJsonFile("appsettings.json")
                    .AddJsonFile("appsettings.Testing.json")
                    .Build()
                )
                .UseStartup<TestStartup>());
_client = _server.CreateClient();
// Act
var response = await _client.GetAsync("/");

// Assert
response.EnsureSuccessStatusCode();

Microsoft也使用HttpClient对此进行了记录:
https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2