How to Write xUnit Test for .net core 2.0 Service

2019-04-02 17:19发布

问题:

I'm new to .net core/C# programming (coming over from Java)

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;


    }
}

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.

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.

But I don't know how I would create a test instance of AutoMapper or a mock of 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.

Thank you for the help.

回答1:

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
}