1

I have a simple question about best practices in unit test verifications. Given this example:


@Test
public void methodUnderTest() {

    when(mockedDependency.someMethod()).thenReturn(someValue);

    int actual = classUnderTest.methodUnderTest();

    assertEquals(5, actual);
    verify(mockedDependency).someMethod();//should I do this?

}

As you can see I'm checking that my mock is being used. Should I do this?

With this verification if I change the implementation of the method (removing the usage of that dependency) my test is gonna fail and I'm forced to remove when and verify.

Without this verification if I change the implementation of the method my test is gonna pass but I will never know that in that test I'm mocking something that is not needed and when I will see that test again I will think that in my implementation I need that dependency.

Thanks in advance.

  • Where/how do you bind the classUnderTest to the mockedDependency? Does the actual result depend on someValue you use to mock? – siegi Dec 17 '17 at 12:56
1

I've asked myself that question many times. I think you have to differentiate (translation: "it depends") between at least two cases:

Case I

The module under test is using the dependency to obtain some values or to perform some helper tasks. For example, GenerateIncomeSheet() might have dependencies on an AccountsRepository and a TaxCalculator.

In this case, do not verify that the dependencies' methods are called. The point of your module is not to use these dependencies, but to provide the correct result.

Case II

Some important, usually state changing operation has to be performed by a dependency. For example, the method under test should perform some checks and - depending on the result - add data to a repository.

In this case, you not only want to verify that the repository's method has been called (with the correct data), but also that it has not been called if the checks fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.