简体   繁体   中英

Mockito Repetition in Stubbing and Verification

It seems that in certain cases, EasyMock stubbing can take the place of verification. Take the following trivial example:

Class A:

public class A {
    private B b;

    public A(B b) {
        this.b = b;
    }

    int main(int input) {
        return b.timesThree(input + 4);
    }
}

Class B:

public class B {
    int timesThree(int input) {
        return input * 3;
    }
}

Class ATest:

@ExtendWith(MockitoExtension.class)
public class ATest {
    @Mock
    B b;

    @InjectMocks
    A a;

    @Test
    void testMain() {
        doReturn(21).when(b).timesThree(7);

        int result = a.main(3);
        assertEquals(21, result);

        verify(b).timesThree(7);
    }

}

Is there a point to the verify call? The when call already asserts the input parameter to b.timesThree() is 7.

In this case no. It comes down to what you are really trying to assert in the test.

Here you are trying to test that when main method is called with a value 2 things should happen

  1. timesThree should be called with value+4

  2. value returned from timesThree should be returned by your main function

Since in your test the below three lines is enough to assert both the above cases you don't need a verify here.

doReturn(21).when(b).timesThree(7);
int result = a.main(3);
assertEquals(21, result);

The easiest way to find out if your test is good enough is by commenting out parts of your implementation and making your test fail (TDD). As long as you get a failing test you are good.

Ex: change 4 to 5 - test fails, remove input test fails

Suppose your timesThree method did not return a value, but instead stored it somewhere

int main(int input) {
//Stores value somwhere
    b.timesThree(input + 4);
}

Here you test has to assert that timesThree is called once with the value 7. In this case you need a verify, since you will never be able to get a failing test without verify.

Also on a side note one of the comments mentioned "the test would pass if the code was replaced by return 21;"

To proof your test against this consider using a random integer instead of hardcoding values. This will make sure there is no accidental hard coding in your implementation. Example library for random intgers https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/RandomUtils.html#nextInt()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM