模拟对象-设置方法-测试驱动开发

模拟对象-设置方法-测试驱动开发

问题描述:

我正在学习测试驱动开发,并尝试使用Moq库进行模拟. Mock类的Setup方法的目的是什么?

I am learning Test Driven Development and trying to use Moq library for mocking. What is the purpose of Setup method of Mock class?

Moq Mock对象的默认行为是对所有方法和属性进行存根.这意味着使用任何参数调用该方法/属性都不会失败,并且将返回特定返回类型的默认值.

The default behaviour of a Moq Mock object is to stub all methods and properties. This means that a call to that method/property with any parameters will not fail and will return a default value for the particular return type.

您出于以下任何或所有原因调用Setup方法:

You call Setup method for any or all of the following reasons:

  • 您想将输入值限制为方法.
public interface ICalculator {
  int Sum(int val1, val2);
}

var mock = new Mock<ICalculator>();
mock.Setup(m=>m.Sum(
  It.IsAny<int>(), //Any value
  3                //value of 3
));

以上设置将使对方法Sum的调用与val1的任何值和val2的3值匹配.

The above setup will match a call to method Sum with any value for val1 and val2 value of 3.

  • 您要返回一个特定值.继续ICalculator示例,以下设置将返回10值,而不管输入参数如何:
  • You want to return a specific value. Continuing with ICalculator example, the following setup will return a value of 10 regardless of the input parameters:
var mock = new Mock<ICalculator>();
mock.Setup(m=>m.Sum(
  It.IsAny<int>(), //Any value
  It.IsAny<int>()  //Any value
)).Returns(10);

  • 设置后,您想使用Mock<T>.VerifyAll()来验证(一次)所有以前的设置.
    • You want to use Mock<T>.VerifyAll() after you setups to verify that all previous setups have been called (once).
var mock = new Mock<ICalculator>();
mock.Setup(m=>m.Sum(
  7, //value of 7
  3                //value of 3
));

mock.Setup(m=>m.Sum(
  5, //value of 5
  3                //value of 3
));

mock.VerifyAll();    

上面的代码验证Sum被调用两次.一次使用(7,3),一次使用(5,3).

The above code verifies that Sum is called twice. Once with (7,3) and once with (5,3).