Writing tests for the business layer

When writing tests for the business layer, we recommend that you avoid using the Spring Framework in the unit tests. This will ensure that your tests are framework independent and will run faster.

The following code is an example of a unit test written without using the Spring Framework:

    @RunWith(MockitoJUnitRunner.class)
public class BusinessServiceMockitoTest {

private static final User DUMMY_USER = new User("dummy");

@Mock
private DataService dataService;

@InjectMocks
private BusinessService service = new BusinessServiceImpl();

@Test
public void testCalculateSum() {

BDDMockito.given(dataService.retrieveData(Matchers.any(User.class)))
.willReturn(Arrays.asList(new Data(10), new Data(15), new Data(25)));

long sum = service.calculateSum(DUMMY_USER);

assertEquals(10 + 15 + 25, sum);

}
}

The Spring Framework is used to wire dependencies in the running application. However, in your unit tests, using the @InjectMocks Mockito annotation in combination with @Mock is the best option.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset