MOQ Mock void方法,用于更改字段值 [英] MOQ Mock void method that changes a field value
问题描述
我是最小起订量和模拟的新手.
假设我有一个像这样的类,带有一个更改值的void方法:
I am new to MOQ and Mocking.
Assume I have a class like this, with a void method that changes a value:
public class Sample
{
public virtual int Number { get; set; }
public virtual void Check(int a)
{
this.Number = a > 10 ? this.Number = 100 : this.Number = 200;
}
}
我想测试void方法,以确保它正在更改本地字段Number
.
I want to test the void method to make sure it is changing the local field Number
.
[Fact]
public void TestSampleClass()
{
var sut = new Mock<Sample>();
sut.Setup(s => s.Number).Returns(50);
sut.Setup(s => s.Check(It.IsAny<int>())).Callback(
(int testNumber) =>
{
if (testNumber > 10)
{
sut.Setup(s => s.Number).Returns(100);
}
else
{
sut.Setup(s => s.Number).Returns(200);
}
});
}
似乎该方法不会将值更改为100或200 ...
如果我打印sut.Object.Number
,它给出的是初始值,而不是void调用后的更新值.
It seems that the method doesn't change the value to 100 or 200...
If I print sut.Object.Number
it gives the initial value, not the updated one after void call.
推荐答案
除非您的示例是一个更为复杂的问题的简化表示,否则无需模拟Sample
类.
Unless your example is a simplified representation of a much more complicated problem, there is no need to mock the Sample
class.
[Fact]
public void TestSampleClass()
{
//Arrange
var testNumber = 5; //Could be what ever number you want to test
var expected = 200
var sut = new Sample();
//Act
sut.Check(testNumber);
var actual = sut.Number;
//Assert
Assert.AreEqual(expected, actual);
}
如果打算学习如何在这种特殊情况下进行这种测试,那么您可以做类似的事情...
If the intention was to learn how to perform such a test in this particular situation then you can do something like this...
假设您要在以下界面上测试Check
方法...
Assuming you wanted to test that the Check
method on the following interface...
public interface ISample {
int Number { get; set; }
void Check(int a);
}
,其中期望的行为是使方法使用Moq
更改属性的值,然后这就是设置它的方法.
where the expected behavior is to have the method change the value of a property using Moq
then this is how you can set it up.
[Fact]
public void TestISampleCheck() {
//Arrange
var testNumber = 5; //Could be what ever number you want to test
var expected = 200;
var mock = new Mock<ISample>();
//Specifies that the all properties on the mock should have "property behavior",
//meaning that setting its value will cause it to be saved and later returned
//when the property is requested. (this is also known as "stubbing"). The default
//value for each property will be the one generated as specified by the Moq.Mock.DefaultValue
//property for the mock.
mock.SetupAllProperties();
var sut = mock.Object;
mock.Setup(s => s.Check(It.IsAny<int>()))
.Callback((int a) => {
if (a > 10) {
sut.Number = 100;
} else {
sut.Number = 200;
}
});
//Act
sut.Check(testNumber);
var actual = sut.Number;
//Assert
Assert.AreEqual(expected, actual);
}
这篇关于MOQ Mock void方法,用于更改字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!