c# moq教學 MOQ模擬void方法,改變字段值




moq教學 (2)

除非你的例子是一個複雜問題的簡化表示,否則不需要模擬Sample類。

[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);
}

如果目的是要學習如何在這種特殊情況下進行這樣的測試,那麼你可以做這樣的事情...

假設你想測試下面的接口上的Check方法...

public interface ISample {
    int Number { get; set; }
    void Check(int a);
}

預期的行為是使該方法使用Moq改變屬性的值,那麼這就是你如何設置它。

[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和Mocking的新手。
假設我有這樣的類,用一個void方法來改變一個值:

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

[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它給出的初始值,而不是更新之後的空值調用。


Callback方法只是設置方法的行為,做一些改變,你實際上需要調用sut.Object.Check(11);方法,即sut.Object.Check(11); ,那麼你可以斷言你的結果。





moq