Unit Testing in Java II

Mercy Jemosop
1 min readJul 21, 2022

--

Mocking your application in Java

Introduction

From the previous unit testing blog, we went through some basics of unit testing. Here is a link to my previous blog.

We going to go over some more mockito methods:

@InjectMocks creates mock implementation and additionally injects the dependent mocks that are marked with the annotations @Mock into it.

Mockito BDD (behavior-driven development) is a style of writing test using //given(setup part),//when( invocation), and //then(readable assert) comments as the primary part of the test body.

@Test  
public void testList_usingBDD() {

//Given - setup part
List<String> mocklist = mock(List.class);
given(mocklist.get(Mockito.anyInt())).willReturn("Mockito");
//When - invocation
String string1 = mocklist.get(0);
//Then - readable assert
assertThat(string1, is("Mockito"));
}

It uses given(…)willReturn(..) method in place of when(…)thenReturn(..) method.

  • <T>given(T methodCall) method is similar to the when(T methodCall) method, it enables stubbing.
  • <T> then(T mock) enables the BDD style verification of mock behavior.

Update the get users method with Specifications and page request

Step 1:

Update the user repository with JpaSpecificationExecutor interface which provides APIs and methods to define Specifications and create Spring Data Jpa Criteria.

Step 2:

Create UserPredicate class which will be used during search and filter when fetching user details. This class implements the specification interface.

step 3: Create a service class for fetching users. To create one service class, remove the UserDataService class and the @override from the methods

@AllArgsConstructor
@Service
public class UserDataServiceImpl{

private final UsersRepository usersRepository;

public Page getUsers(Specification specification, PageRequest pageRequest) {
return usersRepository.findAll(specification,pageRequest);
}
}

step 4: Create test cases for getting users

source code github

Happy Coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy