I am trying to do a unit test with Moq for this method:
public class XsService : EntityResourceService<XModel, string>, IXResourceService<XModel, string>
{
private readonly IXsEntityRepository<XModel, string> XEntityRepository;
Public XsService(
iCorrelationContextAccessor correlationContextAccessor,
IJsonApiContext jsonApiContext,
IXsEntityRepository<XModel, string> XEntityRepository) :
base(jsonApiContext, XEntityRepository)
{
this.XEntityRepository = XEntityRepository;
}
public async Task<IEnumerable<XModel>> GetXsAsync(UModel uModel)
{
await XEntityRepository.GetAllAsync(uModel.UserId);
return await base.GetAsync();
}
}
This is my unit test:
var uModels = new List<UModel>()
{
new UModel { Id = "12341", Name="group_name1" },
new UModel { Id = "12342", Name="group_name1" }
};
[Fact]
public async Task GetUAsync_Ok()
{
//Mocking base class
var baseClassMock = new Mock<XsService>(correlationContextAccessor,
JsonApiContextMock.Object, userGroupsEntityRepositoryMock.Object) { CallBase = true };
baseClassMock.Setup(x => x.GetAsync()).Returns(Task.FromResult(uModels));
// Act
var res = baseClassMock.Object.GetXsAsync(parameter);
// Assert
Assert.Equal("", "");
}
the Error is thrown when reaching the line:
return await base.GetAsync();
Error:
System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=JsonApiDotNetCore StackTrace: at JsonApiDotNetCore.Services.EntityResourceService`3.GetAsyncd__8.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
This exception was originally thrown at this call stack: JsonApiDotNetCore.Services.EntityResourceServiceTResource, TEntity, TId.GetAsync() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Maybe I need to moq EntityResourceService, like this:
var eRS = new Mock<EntityResourceService<UModel, string>>(jsonApiContextMock.Object,
userGroupsEntityRepositoryMock.Object, null);
eRS.Setup(x => x.GetAsync()).Returns(Task.FromResult(userGroupModels));
var x = eRS.Object.GetAsync();
But, how can I inject that into the moq when creating the class instance?
This is the GetAsync method code
// MyModelService.cs
public class MyModelService : IResourceService<MyModel>
{
private readonly IMyModelDao _dao;
public MyModelService(IMyModelDao dao)
{
_dao = dao;
}
public Task<IEnumerable<MyModel>> GetAsync()
{
return await _dao.GetModelAsync();
}
}
User contributions licensed under CC BY-SA 3.0