I am learning JUnit and I am testing a simple method, I have a method which populate a list and return it. Although in unit test I provided the same list, the unit test failed.
Code
public List<Transaction> retrieveData() throws ParseException {
List<Transaction> expResult = new ArrayList();
Date convertedDate = new SimpleDateFormat("yyyy-MM-dd").parse("2014-04-29T13:15:54");
Transaction tran = new Transaction("A", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
tran = new Transaction("B", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
tran = new Transaction("A", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
tran = new Transaction("B", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
return expResult;
}
JUnit
@Test
public void testRetrieveData() throws ParseException {
MyClass instance = new MyClass();
List<Transaction> expResult = new ArrayList();
Date convertedDate = new SimpleDateFormat("yyyy-MM-dd").parse("2014-04-29T13:15:54");
Transaction tran = new Transaction("A", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
tran = new Transaction("B", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
tran = new Transaction("A", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
tran = new Transaction("B", convertedDate,new BigDecimal("20.00"));
expResult.add(tran);
List<Transaction> result = instance.retrieveData();
assertEquals(expResult, result);
}
The failed message and stacktrace are as following
Error
expected: java.util.ArrayList<[
Transaction{cardNumber=A, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00},
Transaction{cardNumber=B, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00},
Transaction{cardNumber=A, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00},
Transaction{cardNumber=B, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00}]>
but was: java.util.ArrayList<[
Transaction{cardNumber=A, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00},
Transaction{cardNumber=B, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00},
Transaction{cardNumber=A, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00},
Transaction{cardNumber=B, timestamp=Tue Apr 29 00:00:00 EST 2014, price=20.00}]>
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:93)
at org.junit.Assert.failNotEquals(Assert.java:647)
at org.junit.Assert.assertEquals(Assert.java:128)
at org.junit.Assert.assertEquals(Assert.java:147)