Reset mock verification in Moq?

前端 未结 8 1649
执笔经年
执笔经年 2021-02-11 12:01

Setup as so:

public interface IFoo
{
    void Fizz();
}

[Test]
public void A()
{
    var foo = new Mock(MockBehavior.Loose);

    foo.Object.Fizz();         


        
8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-11 12:33

    This is indeed unit test abuse as you are verifying two things in one test. Your life would be much easier if you took the ObjectUnderTest initialisation out of the test and into a common setup method. Then your tests become much more readable and independant of each other.

    More than production code, test code should be optimized for readability and isolation. A test for one aspect of system's behavior should not affect other aspects. It really is much much easier to refactor common code into a setup method than to try to reset the mock objects.

    ObjectUnderTest _objectUnderTest;
    
    [Setup] //Gets run before each test
    public void Setup() {
        var foo = new Mock(); //moq by default creates loose mocks
        _objectUnderTest = new ObjectUnderTest(foo.Object);
    }
    [Test]
    public void DoStuffToPushIntoState1ShouldCallFizz() {
        _objectUnderTest.DoStuffToPushIntoState1(); // this is various lines of code and setup
    
        foo.Verify(x => x.Fizz());
    }
    [Test]
    public void DoStuffToPushIntoState2ShouldntCallFizz() {
    {
        objectUnderTest.DoStuffToPushIntoState2(); // more lines of code
        foo.Verify(x => x.Fizz(), Times.Never());
    }
    

提交回复
热议问题