Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug mockito mocks/stubs/matchers?

During normal test development using mockito, I (and many others for sure) run into many situations where our when(service.doSomething(paramMatcher, paramMatcher2, ...).thenReturn(...) drives me crazy. So many combinations that are possible between lists, vargars, null values, etc. it is often hours spent just trying to get the formula right and even then I give up and just use any() with thenAnswer(manual matching).

How can I debug the parameter matching mechanism of mockito? For added difficulty, I run my tests using Mockito runner which means that I use annotation to initialize and automatically inject my mocked services.

like image 781
Pierre Avatar asked Apr 26 '16 15:04

Pierre


People also ask

What is stubbing in Mockito?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.

What is lenient () in Mockito?

lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.

What is the difference between doReturn and thenReturn?

Following are the differences between thenReturn and doReturn : * Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.

What does @mock do in Mockito?

mock() The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.


Video Answer


1 Answers

You can enable verbose logging on your Mocked objects:

List mockWithLogger = mock(List.class, withSettings().verboseLogging())

This should give you more information to understand the interactions.

https://javadoc.io/doc/org.mockito/mockito-core/2.6.4/org/mockito/MockSettings.html#verboseLogging()

like image 168
Glennular Avatar answered Oct 18 '22 17:10

Glennular