JUnit test with Mockito and Spring

Deveop Mockito, Spring and JUnit tests

The code source bellow presents a JUnit test using Spring-test and Mockito framework.

@RunWith(SpringJUnit4ClassRunner.class) runs the test with Spring custom runner that will load Spring application context.
@Autowire associate invoiceService reference to the InvoiceService instance.
@Before annotation executes the setup method before the test.
MockitoAnnotations.initMocks(this) scans the class annotation, instanciates invoiceDaoMock and inject it into the InvoiceService bean.
when(.(any())).thenReturn() associates a return value with method execution parameters.

//Load Spring contexte
@ContextConfiguration(locations = {"classpath:/application-context.xml"})
public class InvoiceServiceTest {
    // Create Mock
    private IInvoiceDao invoiceDaoMock;
    private IInvoiceService invoiceService;
    public void setUp() {
    public void testProcessInvoice() throws SQLException {
        // specify mock behave when method called
        Map<Product, Integer> products = new HashMap<Product, Integer>();
        products.put(new Product("labtop", BigDecimal.valueOf(1255.50)), 2);
        Invoice invoice = invoiceService.processInvoice(products);
        Assert.assertEquals(1255.50 * 2, invoice.getTotal().doubleValue(), 0);


Also look at this post for using @RunWith(MockitoJUnitRunner.class)



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s