Test Class

You can write the JUnit tests manually, but Eclipse supports the creation of JUnit tests via wizards.

For example, to create a JUnit test or a test class for an existing class. Right-click on your new class, select this class in the Package Explorer_ view, right-click on it and select New ▸ JUnit Test Case.

Alternatively you can also use the JUnit wizards available under File ▸ New ▸ Other…​ ▸ Java ▸ JUnit.

Maven Dependency

To use JUnit in your Maven build, add the following dependency to your pom file.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

Available JUnit annotations

Annotation Description
@Test public void method() The @Test annotation identifies a method as a test method.
@Test (expected = Exception.class) Fails if the method does not throw the named exception.
@Test(timeout=100) Fails if the method takes longer than 100 milliseconds.
@Before public void method() This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class).
@After public void method() This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
@BeforeClass public static void method() This method is executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit.
@AfterClass public static void method() This method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@Ignore or @Ignore("Why disabled") Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included. It is best practice to provide the optional description, why the test is disabled.
@SuppressWarnings("unchecked") The @SuppressWarnings annotation type allows Java programmers to disable compilation warnings for a certain part of a program (type, field, method, parameter, constructor, and local variable). Normally warnings are good. However in some cases they would be inappropriate and annoying. So programmers can choose to tell the compiler ignoring such warnings if needed.

The java class to be tested

ExpenseServiceImplTest.java

package service.impl;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.List;

import org.jmock.Expectations;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.jpa.domain.Specification;

import resources.specification.ExpenseSpecification;
import resources.specification.SimplePageRequest;
import sendto.ExpenseSendto;
import service.impl.ExpenseServiceImpl;
import dao.ExpenseDao;
import dao.ExpenseTypeDao;
import dao.ReportDao;
import entity.Expense;
import entity.ExpenseType;
import entity.Report;

public class ExpenseServiceImplTest extends ServiceTest {

    private ExpenseDao expenseDao;
    private ExpenseTypeDao expenseTypeDao;
    private ReportDao reportDao;
    private ExpenseServiceImpl expenseService;
    private Specification<Expense> spec;
    private Report report;
    private ExpenseType expenseType;
    private Expense expense;

    @SuppressWarnings("unchecked")
    @Before
    public void setUp() throws Exception {
        spec = context.mock(Specification.class);
        expenseDao = context.mock(ExpenseDao.class);
        reportDao = context.mock(ReportDao.class);
        expenseTypeDao = context.mock(ExpenseTypeDao.class);
        expenseService = new ExpenseServiceImpl(expenseDao, expenseTypeDao,
                reportDao);
        expense = new Expense();
        expense.setId(1L);
        expense.setTaxAmount(0);
        expense.setTotalAmount(1234);
        report = new Report();
        report.setId(1L);
        expense.setReport(report);
        expenseType = new ExpenseType();
        expenseType.setId(2L);
        expense.setExpenseType(expenseType);

    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testRetrieve() {
        context.checking(new Expectations() {

            {
                exactly(1).of(expenseDao).findOne(spec);
                will(returnValue(expense));
            }
        });
        ExpenseSendto ret = expenseService.retrieve(spec);
        assertEquals(1l, ret.getId().longValue());
        assertEquals(0, ret.getTaxAmount().intValue());
        assertEquals(1234, ret.getTotalAmount().intValue());
        assertEquals(report.getId(), ret.getReport().getId());
        assertEquals(expenseType.getId().longValue(), ret.getExpenseType()
                .getId().longValue());
    }

    @Test
    public void testDelete() {
        context.checking(new Expectations() {

            {
                exactly(1).of(expenseDao).delete(expense);

                exactly(1).of(expenseDao).findOne(spec);
                will(returnValue(expense));
            }
        });
        expenseService.delete(spec);
    }

    @Test
    public void testSave() {

        final ExpenseSendto newEntry = new ExpenseSendto();
        ExpenseSendto.Report rpt = new ExpenseSendto.Report();
        rpt.setId(report.getId());
        ExpenseSendto.ExpenseType expenseTypeSendto = new ExpenseSendto.ExpenseType();
        expenseTypeSendto.setId(expenseType.getId());
        newEntry.setExpenseType(expenseTypeSendto);
        newEntry.setReport(rpt);

        context.checking(new Expectations() {

            {
                exactly(1).of(reportDao).findOne(newEntry.getReport().getId());
                will(returnValue(report));

                exactly(1).of(expenseTypeDao).findOne(
                        newEntry.getExpenseType().getId());
                will(returnValue(expenseType));

                exactly(1).of(expenseDao).save(with(any(Expense.class)));
                will(returnValue(expense));

            }
        });

        ExpenseSendto ret = expenseService.save(newEntry);
        assertEquals(expense.getId(), ret.getId());
        assertEquals(expenseType.getId(), ret.getExpenseType().getId());
        assertEquals(report.getId(), ret.getReport().getId());
    }

    @Test
    public void testUpdate() {
        final ExpenseSendto newEntry = new ExpenseSendto();
        newEntry.setTaxAmount(0);
        newEntry.setTotalAmount(1234);
        context.checking(new Expectations() {

            {
                exactly(1).of(expenseDao).save(expense);
                will(returnValue(expense));

                exactly(1).of(expenseDao).findOne(spec);
                will(returnValue(expense));
            }
        });
        ExpenseSendto ret = expenseService.update(spec, newEntry);
        assertEquals(1l, ret.getId().longValue());
        assertEquals(newEntry.getTaxAmount(), ret.getTaxAmount());
        assertEquals(newEntry.getTotalAmount(), ret.getTotalAmount());
    }

    @Test
    public void testFindAll() {
        final ExpenseSpecification spec = new ExpenseSpecification();
        final SimplePageRequest pageable = new SimplePageRequest(0, 20, "id",
                "ASC");
        final List<Expense> expenses = new ArrayList<Expense>();
        expenses.add(expense);
        final Page<Expense> page = new PageImpl<Expense>(expenses);
        context.checking(new Expectations() {

            {
                exactly(1).of(expenseDao).findAll(spec, pageable);
                will(returnValue(page));
            }
        });
        Page<ExpenseSendto> rets = expenseService.findAll(spec, pageable);
        assertEquals(1, rets.getTotalElements());
        ExpenseSendto ret = rets.iterator().next();
        assertEquals(1l, ret.getId().longValue());
        assertEquals(expense.getTaxAmount(), ret.getTaxAmount());
        assertEquals(expense.getTotalAmount(), ret.getTotalAmount());
    }
}

Now we can run the test case by right-clicking on the test class and select Run As -> JUnit Test.

The program output will turn to green light indicating no errors or failures in the generated code, but if any errors or failure it indicates with brown light in the Junit with failure trace.

Advantages of JUnit

  • Using JUnit we can save testing time.
  • In the web application development we implement JUnit test cases in the DAO classes. DAO classes doesn't require server for testing.
  • JUnit can also test Spring applications but most of the time we test only DAO classes. Even some times service classes also tested using JUnit(as in our example).
  • Since server is not used for testing the testing becomes fast and easy.

results matching ""

    No results matching ""