模拟对象 - 设置方法 - 测试驱动开发 [英] Mock objects - Setup method - Test Driven Development
问题描述
我正在学习测试驱动开发并尝试使用 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)
.
这篇关于模拟对象 - 设置方法 - 测试驱动开发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!