Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write xUnit Test for .net core 2.0 Service that uses AutoMapper and Dependency Injection? [closed]

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.

like image 850
Bruce Phillips Avatar asked Nov 28 '22 13:11

Bruce Phillips


1 Answers

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
}
like image 152
junkangli Avatar answered Dec 28 '22 09:12

junkangli