【问题标题】:why return null Repository implementation for Entity Framework when test mock unit为什么在测试模拟单元时为实体框架返回空存储库实现
【发布时间】:2018-08-03 15:45:20
【问题描述】:

嗨 iam 使用带有 ef 的模拟单元测试 当测试构建时,我的测试在调试测试时失败,我收到以下错误。

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

[测试类] 公共类 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);
}

这是我的代码层服务 我肯定返回 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-core mocking


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多