【发布时间】:2019-08-23 08:38:57
【问题描述】:
我正在尝试测试使用两个不同接口的方法。 使用 Moq 我配置了接口方法并设置了一个返回对象,但是执行的第一个方法返回值,第二个返回 null,无论我设置为什么返回。
这是一个例子:
接口 1
public interface IUserRepository
{
User GetUserById(int id);
}
接口 2
public interface ICallApiService
{
ApiResponseDto ValidateUser();
}
我要测试的课程
public class UserServices : IUserServices
{
private IUserRepository _userRepository;
private ICallApiService _callApiService;
public UserServices(IUserRepository userRepository, ICallApiService callApiService)
{
_userRepository = userRepository;
_callApiService = callApiService;
}
public User GetUserById(int id)
{
//result always have a value set to result
var result = _callApiService.ValidateUser();
//result2 is always null
var result2 = _userRepository.GetUserById(result.UserId);
return result2;
}
}
测试方法
[TestMethod]
public void TestMethod1()
{
moqUserRepository = new Moq.Mock<IUserRepository>();
moqUserRepository.Setup(s => s.GetUserById(1)).Returns(new User() { Id = 100, Birth = DateTime.Now, Email = "g@test.com", Name="g" });
moqCallApiService = new Moq.Mock<ICallApiService>();
moqCallApiService.Setup(s => s.ValidateUser()).Returns(new ApiResponseDto() { Active = true, Messages = "None", UserId = 100 });
var userService = new UserServices(moqUserRepository.Object, moqCallApiService.Object);
var resultInstance = userService.GetUserById(1);
var moqUserService = new Moq.Mock<UserServices>(moqUserRepository.Object, moqCallApiService.Object).Object;
var resultMock = moqUserService.GetUserById(1);
}
在使用实例和模拟的两种情况下,我都会得到相同的错误(返回 null)。
我错过了 Moq 的东西吗?
【问题讨论】:
-
你在哪里设置你的
moqUserService来为GetUserById()返回一些东西? -
所以你期望
moqUserService.GetUserById在你没有模拟该方法时返回一个值? -
你为什么在最后一部分嘲笑
UserServices? -
对于 Mocking 不使用特定的参数值,总是使用泛型的任何整数值,所以它对任何输入值返回相同的东西
-
@MatthewWatson 你是对的,它在我的测试中丢失了。谢谢。
标签: c# unit-testing .net-core interface moq