I'm trying to write a Junit for testing an object that has the current timestamp. the problem is when I first create the current timestamp as the following:
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
It creates a timestamp object with current time including the milliseconds. so when I run my tests they're never equal because there is some time elapsed in milliseconds between the time I created the timestamp object and the time of testing:
x.setTimeToMyMethod(timestamp);
assertEquals(timestamp, x.getTimeFromMyMethod());
I tried to use SimpleDateFormat but it converts the time to a string and my setter method only accept Timestamp objects. Is there anyway that I can overcome this problem? Thanks in advance!
Thanks for the answers and here is my code and hopefully it will clarify what I'm trying to do:
public class myTest {
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
myTestingClass testClass = new myTestingClass();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
testClass.setCreateDate(timestamp);
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
try {
assertEquals(timestamp, testClass.getCreateDate());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
when I try to run it it gives me the following error:
java.lang.AssertionError: expected:<2015-02-11 09:09:40.038> but was:<2015-02-11 09:09:40.04>
I had similar problem recently. Find you question but without accepted answer so I thought to try to answer now since I managed to solve my problem. First of all it would be useful to see code of myTestingClass and especially of setCreateDate(timestamp) method. Reason for your AssertionError is use of two different Timestamps objects. My (big) assumption is that one Timestamp object is created when myTestingClass is instantiate and other in JUnit. And then you compare these two objects. If you would have code like this:
public class myTestingClass {
// other code ...
Timestamp timestamp;
public void setCreateDate(Timestamp timestamp) {
this.timestamp = timestamp;
}
public Timestamp getCreateDate() {
return timestamp;
}
}
then difference between time of creation Timestamp object and moment of testing would be irrelevant because you use one same Timestamp object and test would pass.
P.S. Big portion of Date class is deprecated so you should think of using new classes for same purpose – LocalDate / LocalTime / LocalDateTime (Java 8 and later). Creating Timestamp with LocalDateTime would look like this:
LocalDateTime now = LocalDateTime.now();
Timestamp timestamp = Timestamp.valueOf(now);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With