Mockito is a fantastic mock library for Java. I’m fascinated by how easy
it is to use, compared to other things out there in the Java. To someone who is new to unit testing, the idea of mock objects can be
confusing to say the least. However, in the real world, software has dependencies. We have action
classes that depend on services and services that depend on data access
objects (DAOs) and the list goes on. The idea of unit testing is that we want to test our code without
testing the dependencies. This test allows you to verify that the code
being tested works, regardless of it's dependencies. The theory is that
if the code I write works as designed and my dependencies work as
designed, then they should work together as designed.
If you want to create unit tests to test your code, having an Interface that defines the signature of your Dao also lets you create a "mock" Dao object that you can use in your tests.
As a template, it’s a good practice to view tests like a BDD style test.
The code below would be an example of this:
If you want to create unit tests to test your code, having an Interface that defines the signature of your Dao also lets you create a "mock" Dao object that you can use in your tests.
As a template, it’s a good practice to view tests like a BDD style test.
// Given
// When
// Then
The code below would be an example of this:
- Add the Mockito dependency to your pom.xml:
org.mockito
mockito-all
1.8.4
test
Mockito in JUnit test:
import static org.mockito.Mockito.*;
//...
@Test
public void testMock() { // Given
Map mapMock = mock(Map.class);
// When
when(mapMock.get("1")).thenReturn("1");
when(mapMock.get("2")).thenReturn("2");
Object o = new Object();
mapMock.put("anyObject", o);
//ThenassertEquals("firstValue", mapMock.get("1")); assertEquals("secondValue", mapMock.get("2"));
verify(mapMock).get("1");
verify(mapMock).get("1");
verify(mapMock).put("anyObject", o);
}
That’s it – all you need to know to get started. Mock objects are a very valuable tool in testing. They provide you with the ability to test what you write without having to address dependency concerns.
No comments:
Post a Comment