Java登录接口测试指定异常时出现AssertionError问题求助
Let's break down why your tests are failing and how to fix them:
Key Issues Identified
Argument Mismatch in Mock Setup
Your mock forauthManager.authenticate()uses hardcoded values ("someUsername","somePassword"), but your test passes aJwtRequestwith"someUser"and"somPass". Mockito only triggers the mocked behavior when the arguments exactly match what's expected—so your exception never gets thrown, leading to the AssertionError.Incorrect Verify Argument
Yourverifystatement checks for"some"as the username, but your test uses"someUser"—this would fail even if the exception was thrown correctly.Minor Inconsistency in Test Declaration
Your second test doesn't declarethrows Exception(though this isn't strictly required for runtime exceptions, it's good to align with your first test for consistency).
Corrected Test Code
@Test(expected = BadCredentialsException.class) public void shouldThrowBadCredentialsExceptionWhenTryToAuthWithBadCredential() throws Exception { String testUsername = "someUser"; String testPassword = "somPass"; JwtRequest jwtRequest = new JwtRequest(testUsername, testPassword); // Match the exact arguments passed to authManager when(authManager.authenticate(new UsernamePasswordAuthenticationToken(testUsername, testPassword))) .thenThrow(new BadCredentialsException("bad credentials")); controller.createAuthenticationToken(jwtRequest); // Verify against the correct username verify(service, never()).loadUserByUsername(testUsername); } @Test(expected = DisabledException.class) public void shouldThrowDisabledExceptionWhenTryToAuthWithDisabledUser() throws Exception { String testUsername = "someUser"; String testPassword = "somPass"; JwtRequest jwtRequest = new JwtRequest(testUsername, testPassword); // Match the exact arguments passed to authManager when(authManager.authenticate(new UsernamePasswordAuthenticationToken(testUsername, testPassword))) .thenThrow(new DisabledException("User_disabled")); controller.createAuthenticationToken(jwtRequest); // Verify against the correct username verify(service, never()).loadUserByUsername(testUsername); }
Additional Notes
- If you don't need to test exact credentials (just that any bad credentials trigger the exception), you can use Mockito matchers like
anyString()instead of hardcoding values:when(authManager.authenticate(new UsernamePasswordAuthenticationToken(anyString(), anyString()))) .thenThrow(new BadCredentialsException("bad credentials")); - Ensure your
authManageris properly mocked (using@MockorMockito.mock(AuthenticationManager.class)) in your test class—otherwise you'll get a NullPointerException instead of the intended exception.
内容的提问来源于stack exchange,提问作者snzew

