我在这里已经阅读了所有其他主题,但是找不到正确的解决方案。

我正在测试调用要模拟的服务的控制器。
如果在测试中我控制了when().thenReturn()规则的结果,则可以正常工作。

当我调试并检查所定义的规则在被测系统(即我的控制器)中是否有效且已应用时,该规则根本不会应用,它会返回空值,而不是我想要的值。让我们深入我的代码!

这是我的控制器方法,即被测系统:

@RequestMapping(value = "/login", method = POST)
public ResponseEntity<Object> loginUser(@RequestParam(value ="id") String id, @RequestParam(value="password") String pwd){
   try {
      Optional<User> userr = loginService.getUserFromDbAndVerifyPassword(id, pwd);      //verify the presence into the database
      if (userr.isPresent()) {
         User user = userr.get();
         String jwt = loginService.createJwt(user.getId(), user.getUsername(), user.getPermission(), new Date());
         return ResponseEntity.status(HttpStatus.OK).header("jwt", jwt).body(new JsonResponseBody(HttpStatus.OK.value(),"Success! User logged in." + jwt));
      }
   }catch(UserNotLoggedException e1){
      return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(),"Login failed! Wrong credentials. " + e1.toString()));
   }catch(UnsupportedEncodingException e2){
      return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(),"Login failed! Encoding permission token error. " + e2.toString()));
   }
   return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new JsonResponseBody(HttpStatus.FORBIDDEN.value(),"Login failed! No corrispondence found into the database of users."));
}


这是我的带有测试方法的测试类:

@RunWith(MockitoJUnitRunner.class)
public class RestControllerTest {

   @InjectMocks
   RestController restController;

   @Mock
   LoginService loginService;


   @Test
   public void loginUserWithSuccessTest() throws UserNotLoggedException, UnsupportedEncodingException{
       User user = new User("BDAGPP32E08F205K", "Pippo Baudo", "ILoveSanRemoEncrypted", "conduttore");
       Optional<User> fakeUserOptional = Optional.of(user);
       when(loginService.getUserFromDbAndVerifyPassword("BDAGPP32E08F205K","ILoveSanRemo")).thenReturn(fakeUserOptional);

       String jwt = "aaaa.bbbb.cccc";
       when(loginService.createJwt(user.getId(), user.getUsername(), user.getPermission(), new Date())).thenReturn(jwt);
       //I've tested also: when(loginService.createJwt(any(), any(), any(), any())).thenReturn(jwt);

       //This is TRUE: assertEquals(loginService.createJwt(user.getId(), user.getUsername(), user.getPermission(), new Date()), jwt); TRUE

       //THIS IS THE METHOD BEING TESTED
       ResponseEntity serverResponse = restController.loginUser("BDAGPP32E08F205K","ILoveSanRemo");
       RestController.JsonResponseBody responseBody = restController.new JsonResponseBody(HttpStatus.OK.value(), "Success! User logged in." + jwt);

       assertEquals(serverResponse.getStatusCode(), HttpStatus.OK); //TRUE
       assertThat(serverResponse.getBody(), is(responseBody)); //FALSE because jwt is NULL!!!!
   }
}


因此,Mockito规则在要测试的方法之外起作用。
在里面,loginService.createJwt()给我一个jwt null,而不是尊重我给的规则期望的值。
这是一个非常奇怪的行为。为什么呢?谢谢!

最佳答案

when(loginService.createJwt(user.getId(), user.getUsername(), user.getPermission(), new Date())).thenReturn(jwt);


这几乎总是会失败的,因为在模拟设置和实际调用时日期会有所不同。

when(loginService.createJwt(any(), any(), any(), any()))


这也是狡猾和模糊的。

我会尝试:

import static org.mockito.ArgumentMatchers.*;

...

when(loginService.createJwt(eq(user.getId()), eq(user.getUsername()), eq(user.getPermission()), any(Date.class))).thenReturn(jwt);

07-24 15:13