Tutorial by Examples

Mockito offers a one-size-fits-all mehtod to create mocks of (non-final) classes and interfaces. Dependency mock = Mockito.mock(Dependency.class); This creates a mock instance of Dependency regardless of whether Dependency is a interface or class. It is then possible to stub method calls to tha...
While a simple mock returns null (or defaults for primitives) to every call, it is possible to change that behaviour. Dependency mock = Mockito.mock(Dependency.class, new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { ...
Class under test: public class GreetingsService { // class to be tested in isolation private UserService userService; public GreetingsService(UserService userService) { this.userService = userService; } public String getGreetings(int userId, LocalTime time) { // the...
@Spy annotation (or method) can be used to partially mock an object. This is useful when you want to partially mock behavior of a class. E.g. Assume that you have a class that uses two different services and and you want to mock only one of them and use the actual implementation of the other service...
In your class that is under test, you may have some private fields that are not accessible even through constructor. In such cases you can use reflection to set such properties. This is a snippet from such JUnit test. @InjectMocks private GreetingsService greetingsService = new GreetingsService();...

Page 1 of 1