为什么在测试模拟单元时为实体框架返回null存储库实现

时间:2018-07-29 09:35:14

标签: c# asp.net-core mocking

hi iam与ef一起使用模拟单元测试 当测试构建我的测试失败时,当调试测试我出现以下错误。

  

System.ArgumentNullException:'值不能为空。'

[TestClass] 公共类Role_Test2 {

private Mock<IUserService> _mockRepository;
private IUserService _service;
Mock<IUnitOfEntity> _mockUnitWork;
Mock<ISecurityAuthorizService> _ISecurityAuthorizService;
Mock<IMapper> _mapper;
List<User> listCountry;

[TestInitialize]
public void Initialize()
{
    _mockRepository = new Mock<IUserService>();
    _mockUnitWork = new Mock<IUnitOfEntity>();
    _mapper = new Mock<IMapper>() ;
    _ISecurityAuthorizService = new Mock<ISecurityAuthorizService>() ;

_service = new AdminCentral.NetCore.ServiceLayer.EFServices.UserService(_mockUnitWork.Object, _mapper.Object, _ISecurityAuthorizService.Object);
//    _service = new UserService(_mockUnitWork.Object, _mockRepository.Object);
    listCountry = new List<User>() {
   new User() { IdCode = 1, Name = "US" },
   new User() { IdCode = 2, Name = "India" },
   new User() { IdCode = 3, Name = "Russia" }
  };
}

[TestMethod]
public void Country_Get_All()
{
    //Arrange
    _mockRepository.Setup(x => x.count(10)).Returns(listCountry);

    //Act
    List<User> results = _service.count(10) as List<User>;

    //Assert
    Assert.IsNotNull(results);
    Assert.AreEqual(3, results.Count);
}

这是我的代码layerservic 我肯定会返回null IUnitOfEntity

  public class UserService : BaseService, IUserService
        {
            #region Fields
              private readonly IUnitOfEntity _iUnitOfEntity;
              private readonly DbSet<User> _users;
              private readonly IMapper _mapper;
              private readonly ISecurityAuthorizService _iSecurityAuthorizService;
            #endregion


            public UserService(IUnitOfEntity unitOfEntity, IMapper mapper,   ISecurityAuthorizService isecurityauthorizservice)
            {
                _iUnitOfEntity = unitOfEntity;
                _users = _iUnitOfEntity.Set<User>();
                _mapper = mapper;
                _iSecurityAuthorizService = isecurityauthorizservice;
            }
       public IList<User> count(int id)
            {
                   return _users.Where(x => x.UserId == id).ToList();
            }

1 个答案:

答案 0 :(得分:0)

在UserService _iUnitOfEntity.Set<User>()的构造函数中被调用,但是,该方法并未被模拟,并且将根据执行情况抛出异常或返回null。 您可能需要添加一个模拟实现,该实现将返回用户列表

//Arrange
_mockRepository.Setup(x => x.count(10)).Returns(listCountry);
_mockUnitWork.Setup(x => x.Set()).Returns(listUsers);