【发布时间】:2019-07-31 08:26:48
【问题描述】:
如何在集成测试中进行依赖注入?
调用departmentRepository 或departmentAppService,给我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>();
调试和设置断点,调用这个仓库或者app服务都是null,
新方法
[Fact]
var departmentDto = await departmentAppService.GetDepartmentById(2);
应用服务的构造函数
DepartmentAppService(departmentRepository, mapper)
DepartmentRepository(dbcontext)
错误:
消息:System.NullReferenceException:对象引用未设置为 一个对象的实例。
【问题讨论】:
-
@Izzy 我可以在实际程序中运行依赖注入,但不能在 xunit 中运行,您的链接不相关,并导致出现问题,谢谢
-
看看here
-
顺便可以用这个
services.AddTransient<IRepository<>, BaseRepository<>>(); -
Unit Testing IServiceCollection Registration 的可能重复项,这说明了如何使用依赖注入进行单元测试
标签: c# asp.net-core .net-core xunit