首页 > 解决方案 > 为什么在测试模拟单元时为实体框架返回空存储库实现

问题描述

嗨,我在测试构建时使用带有 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);
}

这是我的代码 layerservice 我肯定返回 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();
            }

标签: c#asp.net-coremocking

解决方案


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

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

推荐阅读