Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit with new Date()

What would the junit test be when i have the following method:

@Override
public void saveLastSuccesfullLogin(final User user) {
    gebruiker.setLastLogin(new Date());
    storeUser(user);
}

submethode storeUser:

@Override
public void storeUser(final User user) {
    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();
    em.merge(user);
    em.getTransaction().commit();

    em.close();
}

The problem i have is the date, being set for the entity user and then stored. Im using junit and easymock.

like image 412
A.Khan Avatar asked Feb 23 '11 14:02

A.Khan


2 Answers

Try pulling the new Date() into a method with default access specifier like below

@Override
public void saveLastSuccesfullLogin(final User user) {
    gebruiker.setLastLogin(getDate());
    storeUser(user);
}
Date getDate() {
    return new Date();
}

In your test class override the class as below using a mock or stubbed date.

<ClassUnderTest> classUnderTest = new <ClassUnderTest> () {
  @Override 
  Date getDate() {
    return mockDate;
  } 
}

In this way you can assert the date value easily as it is going to be stubbed out.

like image 189
Vinod R Avatar answered Nov 17 '22 04:11

Vinod R


What's the problem with the Date? That you don't know what it is to assert later? A few alternatives:

  1. Pass the date into the method
  2. Create a factory to get the current date/time so you can mock it out
  3. Assert the date within a threshold of correctness
like image 45
Jeanne Boyarsky Avatar answered Nov 17 '22 05:11

Jeanne Boyarsky