What’s the difference between Mockito Matchers isA, any, eq, and same?

any() checks absolutely nothing. Since Mockito 2.0, any(T.class) shares isA semantics to mean “any T” or properly “any instance of type T“. This is a change compared to Mockito 1.x, where any(T.class) checked absolutely nothing but saved a cast prior to Java 8: “Any kind object, not necessary of the given class. The class argument … Read more

What is the best way to unit-test SLF4J log messages?

Create a test rule: import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.slf4j.LoggerFactory; import java.util.List; import java.util.stream.Collectors; public class LoggerRule implements TestRule { private final ListAppender<ILoggingEvent> listAppender = new ListAppender<>(); private final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); @Override public Statement apply(Statement base, Description description) { return new Statement() { @Override … Read more

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method. thenReturn(T value) Sets a return value to be returned when the method is called. @Test public void test_return() throws Exception { Dummy dummy = … Read more

How do I mock a REST template exchange?

You don’t need MockRestServiceServer object. The annotation is @InjectMocks not @Inject. Below is an example code that should work @RunWith(MockitoJUnitRunner.class) public class SomeServiceTest { @Mock private RestTemplate restTemplate; @InjectMocks private SomeService underTest; @Test public void testGetObjectAList() { ObjectA myobjectA = new ObjectA(); //define the entity you want the exchange to return ResponseEntity<List<ObjectA>> myEntity = new … Read more