Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: How to identify unused .when() in Tests

I just refactored many parts of code by simplifying things. Now I need to refactor the tests as well to make them green again, which is not that hard.

But now I struggle a bit as I saw that I don't need some of my .when() declarations anymore as these Mocks won't be called anymore. The thing is they don't make my test red, so I can only identify them by carefully going through each test and compare it to the code, which is kind of annoying and lead to letting it be like that.

Is there any possibilty to make unused .when()'s throwing an error or such? Like a verify which never happens? It would be enough to do it like in setUp: Mockito.enableDebugMode() or whatever, maybe there is such a possibility? ..

Best

like image 532
BAERUS Avatar asked Aug 29 '14 08:08

BAERUS


2 Answers

This feature has been added to Mockito 2.1.0 (https://github.com/mockito/mockito/issues/384).

The default JUnit Rule configuration is to log a warning in the console :

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();

But you can even make your tests fail by increasing the strictness :

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
like image 84
Thomas Naskali Avatar answered Sep 28 '22 07:09

Thomas Naskali


Option 1 You can remove the calls to when() from your tests one at a time (as suggested by @ponomandr) until they fail. A failed test means you add the call to when() back into your test as it must be required.

Option 2 Although you could also approach this problem by adding verify() assertions for every call to when() (as suggested by @HansiKrankl) it means adding more code (fluff) to your test cases.

Option 3 As another alternative you can you use a code coverage tool like Emma whichi you can run from your IDE. It would then be the case of running the test and then seeing whether the calls are being made in your class under test.

Option 4 There are other suggestions around attempting to count the number of invocations.

Personally I would go with Option 1 and starting cleaning up the tests one by one. You will gain a better understanding of the tests looking at them one-by-one and it's an opportunity to clean them up so they are more maintainable.

like image 29
Brad Avatar answered Sep 28 '22 05:09

Brad