JUnit, Mockito library, Spring Boot Testing - Yash-777/MyWorld GitHub Wiki
JUNIT
π TL;DR
- β
Use
@RunWith(MockitoJUnitRunner.class) β JUnit 4 Style
for JUnit 4- You can use only one
@RunWith
, so you canβt combine it with other runners like Parameterized, etc.
- You can use only one
- β
Use
@ExtendWith(MockitoExtension.class) β JUnit 5 Style
for JUnit 5- You can combine with other extensions: e.g.,
@ExtendWith(SpringExtension.class)
for Spring Boot testing.
- You can combine with other extensions: e.g.,
- β Don't use both together β they serve the same purpose but for different frameworks
@Controller public class UserController {
@Autowired private UserService userService;
public String getUserFullName(int userId) {
User user = userService.getUserById(userId);
return user.getFirstName() + " " + user.getLastName();
}
}
@Service
public class MyService {
public User getUserById(int userId) {
return User.builder().firstName("Yash").lastName("M").build();
}
public int multiplyNumbers(int a, int b) {
int sum = addNumbers(a, b);
return a * b * sum;
}
private int addNumbers(int a, int b) {
return a + b;
}
}
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(MockitoExtension.class)
public class MyServiceTest {
@InjectMocks // Test Class
private MyService myService;
@Test
public void testMultiplyNumbers() {
int expected = 30;
int result = myService.multiplyNumbers(2, 3);
assertEquals(expected, result);
}
@Test
public void testAddNumbers() throws Exception {
int expectedSum = 5;
int sum = (int) ReflectionTestUtils.invokeMethod(myService, "addNumbers", 2, 3);
assertEquals(expectedSum, sum);
}
}
//String userName = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
private void loggedInUser() { // org.mockito.Mockito
org.springframework.security.core.context.SecurityContext securityContext = mock(SecurityContext.class);
org.springframework.security.core.Authentication authentication =
mock(org.springframework.security.authentication.UsernamePasswordAuthenticationToken.class);
when(authentication.getPrincipal()).thenReturn("JUnitTestUser");
when(securityContext.getAuthentication()).thenReturn(authentication);
org.springframework.security.core.context.SecurityContextHolder.setContext(securityContext);
}
//Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.
private void request(String payLoad) throws java.io.IOException {
// Mock behavior for HttpServletRequest
HttpServletRequest request = mock(HttpServletRequest.class);
JsonRequestWrapper jsonRequestWrapper = new JsonRequestWrapper(request, payLoad);
ServletInputStream servletInputStream = jsonRequestWrapper.getInputStream();
lenient().when(request.getInputStream()).thenReturn(servletInputStream);
}
public class JsonRequestWrapper extends HttpServletRequestWrapper {
private final String jsonRequestBody;
public JsonRequestWrapper(HttpServletRequest request, String jsonRequestBody) {
super(request); this.jsonRequestBody = jsonRequestBody;
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(jsonRequestBody.getBytes());
return new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
// Implement as needed
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}