我是一名学生,对于一个项目,我必须编写使用 C# 进行的测试。在这里,我必须使用我编写的服务。如何在 C# 单元测试中添加正派注入? 另外我必须使用 AutoMapper,这是否以同样的方式工作?
这是我试过的:
public class DiveTests
{
private readonly IDiveService _diveService;
private readonly IMapper _mapper;
public DiveTests(IDiveService diveService, IMapper mapper)
{
_diveService = diveService;
_mapper = mapper;
}
[Fact]
public async void AddAsync_InputGoodDive_CreateNewDive()
{
Guid id = Guid.Parse("00000000-0000-0000-0000-000000000000");
DateTime dateTime = DateTime.Parse("2020-12-23T17:04:43.802Z");
Dive dive = new Dive()
{
Id = id,
Depth = 15,
DiveDate = dateTime,
DivePlace = "hello"
};
DiveRequestDto diveRequestDto = _mapper.Map<DiveRequestDto>(dive);
await _diveService.AddAsync(diveRequestDto);
var result = await _diveService.GetByIdAsync(id);
Assert.Equal(result.Id, id);
}
}
这是我尝试过的另一个构造函数:
public DiveTests()
{
if (_mapper == null)
{
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new AutoMapperProfiles());
});
IMapper mapper = mappingConfig.CreateMapper();
_mapper = mapper;
_diveService = diveService;
}
}
答案 0 :(得分:0)
如果您要为 IDiveService/DiveService 添加单元测试;那么无需在单元测试中调用 /use IMapper:AddAsync_InputGoodDive_CreateNewDive()
公共课程 DiveTests { 私有只读 IDiveService _diveService;
public DiveTests()
{
_diveService = new DIveSevice(); // or can create this instance at unit test level
}
[Fact]
public async void AddAsync_InputGoodDive_CreateNewDive()
{
// ARRANGE
Guid id = Guid.Parse("00000000-0000-0000-0000-000000000000");
DateTime dateTime = DateTime.Parse("2020-12-23T17:04:43.802Z");
DiveRequestDto diveRequestDto = new DiveRequestDto
{
Depth = 15,
DiveDate = dateTime,
DivePlace = "hello"
};
// ACT
await _diveService.AddAsync(diveRequestDto);
var result = await _diveService.GetByIdAsync(id);
// ASSERT
Assert.Equal(result.Id, id);
}
}