Issue
I want to write a unit test for checking expiration of JWT. I used Mockito.spy to throw an exception, but not works. So far, here is my progress:
@Test
public void hello_fail_expired_token() throws Exception {
User user = FakeDataGenerator.generateFakeUser();
User registeredUser = userService.register(user.getEmail(), user.getPassword(), user.getName());
String token = jwtService.generateToken(registeredUser);
Mockito.doThrow(new JWTExpiredException()).when(Mockito.spy(jwtService)).verifyToken(token);
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.get("/user/hello")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token);
System.out.println(mockMvc.perform(mockRequest).andReturn().getResponse().getContentAsString());
}
After the execution of this method, no exception is throwed. What is my fault?
Solution
I figured out. Before:
@Autowired
JWTService jwtService;
Now:
@Spy
JWTService jwtService;
And in test method, before:
Mockito.doThrow(new JWTExpiredException()).when(Mockito.spy(jwtService)).verifyToken(token);
After:
Mockito.doThrow(new JWTExpiredException()).when(jwtService).verifyToken(token);
Answered By - Jan Franco