Java Reference
In-Depth Information
methods. The first one, which tests when no customers are returned from the delegate, is very easy; see
Listing 12-6.
Listing 12-6.
testReadNoCustomers()
…
@Test
public void testReadNoCustomers() throws Exception {
assertNull(reader.read());
}
…
Wait, that's it? What happened? There is a lot more happening under the covers of this extremely
simple test method than meets the eye. When you execute this method,
CustomerStatementReader
's
read
method is called. In there, Mockito returns
null
when the mock ItemReader's
read
method is called on
line 40. By default, if you don't tell Mockito what to return when a method is called on a mock object, it
returns a type-appropriate value (
null
for objects,
false
for
boolean
s,
-1
for
int
s, and so on). Because
you want your mock object to return
null
for this test, you don't need to tell Mockito to do anything for
you. Aftre Mockito returns
null
from the ItemReader you injected, the logic returns
null
as required.
Your test verifies that the reader returns
null
with JUnit's
Assert.assertNull
method.
The second test method you need to write for the
read
method of
CustomerStatementReader
tests
that the
Statement
object is being built correctly when a customer is returned. In this scenario, because
you aren't working with a database, you need to tell Mockito what to return when
tickerDao.getTotalValueForCustomer
and
tickerDao.getStocksForCustomer
are called with the
customer's id. Listing 12-7 shows the code for the
testReadWithCustomer
method.
Listing 12-7.
testReadWtihCustomer
…
@SuppressWarnings("serial")
@Test
public void testReadWithCustomer() throws Exception {
Customer customer = new Customer();
customer.setId(5l);
when(customerReader.read()).thenReturn(customer);
when(tickerDao.getTotalValueForCustomer(5l)).thenReturn(
new BigDecimal("500.00"));
when(tickerDao.getStocksForCustomer(5l)).thenReturn(
new ArrayList<Transaction>() {
{
add(new Transaction());
}
});
Statement result = reader.read();
assertEquals(customer, result.getCustomer());
assertEquals(500.00, result.getSecurityTotal().doubleValue(), 0);
assertEquals(1, result.getStocks().size());
}
…