c# - 为什么在测试模拟单元时为实体框架返回空存储库实现
问题描述
嗨,我在测试构建时使用带有 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();
}
解决方案
但是,在调用UserService 的构造函数_iUnitOfEntity.Set<User>()
时,该方法没有被模拟,并且会根据实现抛出异常或返回 null。您可能需要添加一个返回用户列表的模拟实现
//Arrange
_mockRepository.Setup(x => x.count(10)).Returns(listCountry);
_mockUnitWork.Setup(x => x.Set()).Returns(listUsers);
推荐阅读
- algorithm - 列表中非重复元素的最小值,在线性时间内
- html - 如何渲染一个
JSF 2.2 中的标记? - stanford-nlp - 斯坦福 CoreNLP 旧版本
- firebird - Firebird 2.5.8、3.0.4 unicode_ci_ai 索引问题
- c# - 不会从 Angular 5 触发 Web API
- javascript - 如何在 React Native 中从一个屏幕切换到另一个屏幕时使用动画进行屏幕转换?
- javascript - 如何在 php.ini 的登录屏幕中显示警报框。如果用户为此代码输入了错误的密码或用户名
- c# - NUnit 中 DbContextOptionsBuilder 的数据类型
- api - 从相扑逻辑下载数据时 curl 失败
- javascript - 使 react-leaflet 可以离线使用