samedi 29 juin 2013

How to test dates in java unit tests?

Testing dates in unit tests is not always an easy stuff. Take a look to the following method, I will then explain you what is the main problem you can encounter.

public class UserService {
  @Inject
  private UserEventDao userEventDao;

  @Inject
  private DateUtility dateUtility;

  public void createCreationUserEvent(User user) {
    UserEvent event = new UserEvent();
    event.setUser(user);
    event.setUserEventType(UserEventType.CREATION);
    event.setEventDate(new Date());
    userEventDao.create(event);
  }
}

To test this method, you have to check that the UserEvent object passed to the UserEventDao.create method is correctly filled. For that you can use a mock framework like Mockito and write the following test :

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
  @InjectMocks
  private UserService userService;

  @Mock
  private UserEventDao userEventDao;

  @Test
  public void createCreationUserEvent_withCorrectParameters_shouldCreateAnEvent() {
    // Given
    User user = new User();

    // When
    userService.createCreationUserEvent(user);

    // Then
    UserEvent expectedUserEvent = new UserEvent();
    expectedUserEvent.setUser(user);
    expectedUserEvent.setUserEventType(UserEventType.CREATION);
    expectedUserEvent.setEventDate(new Date());

    verify(userEventDao).create(expectedUserEvent);
    verifyNoMoreInteractions(userEventDao);
  }
}

The problem is that this test is not in success all the time because the Date object precision is in milliseconds and you can have a little difference between the date created in the method and the date created in the test.

The solution to resolve that is to be sure to manipulate the same Date object between the method and your test. Of course you could add a Date argument in your createCreationUserEvent method but this would just move our problem to the calling method.

I recommend you two solutions to do that : the first one is to use PowerMock and the second one is to create a DateUtility class.

Solution 1 : Using PowerMock

PowerMock is a mock framework allowing you to mock what cannot be mocked by others frameworks : static method calls, private methods, object constructions etc. To do that, Powermock manipulates the bytecode of the class to test.

So in our example, it can mock the new Date() call :
@RunWith(PowerMockRunner.class)
@PrepareForTest(UserService.class)
public class UserServiceTest {

  @InjectMocks
  private UserService userService;

  @Mock
  private UserEventDao userEventDao;

  @Test
  public void createCreationUserEvent_withCorrectParameters_shouldCreateAnEvent()
  throws Exception {
    // Given
    User user = new User();
    Date eventDate = new Date();
    whenNew(Date.class).withNoArguments().thenReturn(eventDate);

    // When
    userService.createCreationUserEvent(user);

    // Then
    UserEvent expectedUserEvent = new UserEvent();
    expectedUserEvent.setUser(user);
    expectedUserEvent.setUserEventType(UserEventType.CREATION);
    expectedUserEvent.setEventDate(eventDate);

    verify(userEventDao).create(expectedUserEvent);
    verifyNoMoreInteractions(userEventDao);
  }
}

As you surely noticed, we use the PowerMock runner and a PrepareForTest annotation which indicates to Powermock that the UserService class bytecode must be modified.

You can now be sure that your test will be in success at each execution.

Solution 2 : Creating a date utility class

In this solution, the concept is to delegate the creation of the date to a new class :

public class DateUtility {
  public Date getCurrentDate() {
    return new Date();
  }
}

And to use this class in UserService :

public class UserService {

  @Inject
  private UserEventDao userEventDao;

  @Inject
  private DateUtility dateUtility;
  
  public void createCreationUserEvent(User user) {
    UserEvent event = new UserEvent();
    event.setUser(user);
    event.setUserEventType(UserEventType.CREATION);
    event.setEventDate(dateUtility.getCurrentDate());
    userEventDao.create(event);
  }
}

Then we can mock the call to DateUtility in our unit test :

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {

  @InjectMocks
  private UserService userService;

  @Mock
  private UserEventDao userEventDao;
  
  @Mock
  private DateUtility dateUtility;

  @Test
  public void createCreationUserEvent_withCorrectParameters_shouldCreateAnEvent() {
    // Given
    User user = new User();
    Date eventDate = new Date();
    doReturn(eventDate).when(dateUtility).getCurrentDate();

    // When
    userService.createCreationUserEvent(user);

    // Then
    UserEvent expectedUserEvent = new UserEvent();
    expectedUserEvent.setUser(user);
    expectedUserEvent.setUserEventType(UserEventType.CREATION);
    expectedUserEvent.setEventDate(eventDate);

    verify(userEventDao).create(expectedUserEvent);
    verifyNoMoreInteractions(userEventDao);
  }
}

Like in the Powermock solution, you can now be sure that your test will be in success at each execution.

Conclusion : Powermock vs DateUtility

Firstly, these two solutions can be applied to every other case where you have to manipulate dates. It works all the time.

The advantage of the Powermock solution is that you don't have to modify your business code to write a good test. However, the bytecode manipulation done by the framework is expensive in term of execution time : in my environment, this simple test needs about 400 ms to be executed whereas the test with Mockito needs almost 0 ms. On more complicated tests with several static classes mocked, this execution time can be even worst : I already saw entire tests classes executed in almost 8 seconds, which can be very problematic in term of productivity.

Concerning the DateUtility solution,  I think it is elegant to have a class with the responsability to manipulate dates. With that, you shouldn't have any "new Date()" call or Calendar manipulation in other classes. And of course, the main bonus is that you can write a good unit test. I would so recommend you this solution!

I hope you enjoyed this thread and I would be very glad to hear which others tricks do you use to test your dates. Also, I you encounter a case where the DateUtility solution cannot help you, I would love to help you.

jeudi 13 juin 2013

Tips to write maintainable unit tests

Because unit tests are considered by a lot of developers as a waste of time, they make no efforts to write a code of quality. It is perhaps not a problem for the developer to understand his tests while he is developing his feature. But when he needs to modify the feature behavior and therefore his tests several weeks later, he will encounter some difficulties to understand his own tests and it will be expensive to modify them.

However it is easy to write a readable and maintainable unit test. You just have to follow several tips.

Tip #1 : give a comprehensive name to each test

Your unit test name should be comprehensive enough to understand which method you are testing and which case you are testing. To achieve that, three information are mandatory in your method name :
  • the name of the tested method
  • the input parameters of the tested method
  • what is the expected behavior of the tested method
If you respect this rule, it is not mandatory anymore to write other documentation (like javadoc in Java). The method name is comprehensive enough. For example :

 @Test  
 public void filterInvalidUsers_withAnInvalidUser_shouldReturnAnEmptyList() {  
 }   

Ok I understand you can be chocked to see an underscore in the method name. But it is a little trick to improve the visibility of what your test is doing. Moreover you can easily identify if you have forgotten a case using the method listing of your favorite IDE :


Tip #2 : use Given / When / Then template

Every unit test has three sections of instructions :
  • the test preparation
  • the call to the tested method
  • the assertions
In some unit tests, it is not always obvious to find these sections. So a little trick to easily identify them is to comment the beginning of each section. "Given" for the test preparation, "When" for the call to the tested method, and "Then" for the assertions. Doing that for each of yours unit tests give a kind of template easily understandable by every developer. For example :

@Test  
public void filterInvalidUsers_withAnInvalidUser_shouldReturnAnEmptyList() {  
   // Given  
   User user = new User();  
   user.setName("userName");  
   user.setBirthDate(new Date());  
   user.setStatus(-1);

   // When  
   List<User> users = userService.filterInvalidUsers(Arrays.asList(user));       

   // Then  
   assertNotNull(users);  
   assertTrue(users.isEmpty());   
 }   

Tip #3 : use reusable methods for the Given and Then sections 

Even if it is logical to factorize your code, this basic coding principle is not always applied to the unit tests. Some developers prefer to copy & paste an entire unit test, just change the test name and one of the assertions, whereas they could create an utility method used by several tests.

An exemple of factorization of our test method could be :

@Test  
public void filterInvalidUsers_withAnInvalidUser_shouldReturnAnEmptyList() {  
   // Given  
   User user = createUserWithCorrectParameters();  
   user.setStatus(-1);

   // When  
   List<User> users = userService.filterInvalidUsers(Arrays.asList(user));       

   // Then
   assertThatThereIsNoUser(users);     
 } 

private User createUserWithCorrectParameters() {
   User user = new User();  
   user.setName("userName");  
   user.setBirthDate(new Date());  
   user.setStatus(10);
   return user;
}

private void assertThatThereIsNoUser(List<User> users) {
   assertNotNull(users);  
   assertTrue(users.isEmpty()); 
}      

 

Tip #4 :  mock all interactions to other objects

An important principle of the unit tests is to test only the behavior of the tested class, and not the behavior of all the objects used by this class. If you don't respect this principle, you could have impacts on several test classes each time you change the behavior of a single class, which is a waste of time.

To do that you can mock every other objects used by the tested class. Mock an object means simulate his behavior and not do a real call to the object. Great Java librairies allow to do this job, for example Easymock or Mockito. I will do a comparative of these two solutions in another thread.

 

Tip #5 : use partial mocking to have smaller tests 

Imagine you want to add a createUsers method in the same class of the filterInvalidUsers method :

public void createUsers(List<User> users) {
    List validUsers = filterInvalidUsers(users);
    if (! validUsers.isEmpty()) {
        userDao.createUsers(validUsers);
    }
}

You have already written your unit tests on filterInvalidUsers and you don't want to write them again. How can you avoid that? A solution is to use partial mocking. Whereas classic mocking allows you to mock the objects used in your tested class, the partial mocking allows you to mock a method in the class you are testing. So you can simulate the call to the method then verify that the call has been performed. For example, in the createUsers unit tests, you can mock the call to the filterInvalidUsers. In Java, EasyMock and Mockito both allow to do partial mocking.

 

Conclusion

 I hope theses few tips will help you to write more maintainable unit tests. Don't hesitate to share your own techniques by commenting this thread. I would be very glad to share with you.