【问题标题】:Mocking class with multiple interfaces具有多个接口的模拟类
【发布时间】: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


【解决方案1】:

当输入参数 id 的值为 1 时,您正在指示存储库模拟返回一个对象。但服务代码调用存储库时的值为 result.UserId,另一个模拟将其设置为 100设置调用。

将第一个设置调用更改为

moqUserRepository.Setup(s => s.GetUserById(100)).Returns(new User() { Id = 100, Birth = DateTime.Now, Email = "g@test.com", Name="g" });

或者使用It.IsAny,因为当你只对方法进行一次模拟调用时,你并不真正关心值:

moqUserRepository.Setup(s => s.GetUserById(It.IsAny<int>())).Returns(new User() { Id = 100, Birth = DateTime.Now, Email = "g@test.com", Name="g" });

【讨论】:

  • It.IsAny&lt;int&gt;() 应该是首选方法,而不是硬编码值
  • 谢谢。我完全错过了。
猜你喜欢
  • 2015-12-14
  • 2011-05-15
  • 1970-01-01
  • 2021-04-30
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多