gpt4 book ai didi

java - 使用 Mockito 进行单元测试

转载 作者:行者123 更新时间:2023-12-01 17:22:31 47 4
gpt4 key购买 nike

我是单元测试的新手,我正在努力理解应该如何完成它。我有一些使用 @RequestParam 的方法,但我不知道如何模拟它。如果我有一个可以应用于其他方法的示例,那就太好了。

你能帮我写一下这个测试方法吗?这将非常有用。

    @PutMapping("/player/update-password")
public ResponseEntity<?> updatePlayerPassword(@RequestParam("token") String token, @RequestParam("password") String newPassword) throws URISyntaxException {
String message = bundle.getString("put_player");
log.debug(message, token, newPassword);
PlayerEntity player = playerService.updatePassword(token, newPassword);
return new ResponseEntity<>(PlayerMapper.INSTANCE.mapPlayer(player), HttpStatus.ACCEPTED);
}

谢谢。

最佳答案

您可以使用@Mock@InjectMocks注释。有了它,您可以将模拟注入(inject)到您的 Controller 中。

@Mock
PlayerService playerServiceMock;

并使用 Mockito 内部测试或方法中的 when().then() 以及 @Before 注释:

when(playerServiceMock.updatePassword(anyString(), anyString())).thenReturn(playerEntity);

对于bundle.getString("put_player")也可以做同样的事情

关于java - 使用 Mockito 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61267533/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com