问题描述
我是.net核心/C#编程的新手(来自Java)
I'm new to .net core/C# programming (coming over from Java)
我有以下Service类,该类使用依赖项注入来获取AutoMapper对象和数据存储库对象,以用于创建SubmissionCategoryViewModel对象的集合:
I have the following Service class the that uses dependency injection to get an AutoMapper object and a data repository object for use in creating a collection of SubmissionCategoryViewModel objects:
public class SubmissionCategoryService : ISubmissionCategoryService
{
private readonly IMapper _mapper;
private readonly ISubmissionCategoryRepository _submissionCategoryRepository;
public SubmissionCategoryService(IMapper mapper, ISubmissionCategoryRepository submissionCategoryRepository)
{
_mapper = mapper;
_submissionCategoryRepository = submissionCategoryRepository;
}
public List<SubmissionCategoryViewModel> GetSubmissionCategories(int ConferenceId)
{
List<SubmissionCategoryViewModel> submissionCategoriesViewModelList =
_mapper.Map<IEnumerable<SubmissionCategory>, List<SubmissionCategoryViewModel>>(_submissionCategoryRepository.GetSubmissionCategories(ConferenceId) );
return submissionCategoriesViewModelList;
}
}
我正在使用Xunit编写单元测试.我无法弄清楚如何为方法GetSubmissionCategories编写单元测试,并让我的测试类提供IMapper实现和ISubmissionCategoryRepository实现.
I'm writing my unit tests using Xunit. I cannot figure out how to write a unit test for method GetSubmissionCategories and have my test class supply an IMapper implementation and a ISubmissionCategoryRepository implementation.
到目前为止,我的研究表明我可以创建依赖对象的测试实现(例如SubmissionCategoryRepositoryForTesting),也可以使用模拟库来创建依赖关系接口的模拟.
My research so far indicates that I could either create a test implementation of the dependent objects (e.g. SubmissionCategoryRepositoryForTesting) or I can use a mocking library to create a mock of the dependency interface.
但是我不知道如何创建AutoMapper的测试实例或AutoMapper的模拟.
But I don't know how I would create a test instance of AutoMapper or a mock of AutoMapper.
如果您知道任何优秀的在线教程,其中详细介绍了如何创建单元测试,其中要测试的类使用AutoMapper和依赖项注入来存储数据仓库,那就太好了.
If you know of any good online tutorials that walk through in detail how to create a unit test where the class being tested uses AutoMapper and dependency injection for a data repository that would be great.
谢谢您的帮助.
推荐答案
此代码段应为您提供一个开端:
This snippet should provide you with a headstart:
[Fact]
public void Test_GetSubmissionCategories()
{
// Arrange
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new YourMappingProfile());
});
var mapper = config.CreateMapper();
var repo = new SubmissionCategoryRepositoryForTesting();
var sut = new SubmissionCategoryService(mapper, repo);
// Act
var result = sut.GetSubmissionCategories(ConferenceId: 1);
// Assert on result
}
这篇关于如何为使用AutoMapper和依赖注入的.net core 2.0服务编写xUnit测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!