简体   繁体   English

使用 Mockito 进行单元测试

[英]Unit tests using Mockito

I'm new to unit tests and well, I'm struggling to understand how it should be done.我是单元测试的新手,而且我正在努力理解它应该如何完成。 I have some methods with @RequestParam and I'm not sure how to mock this.我有一些使用@RequestParam 的方法,但我不确定如何模拟它。 It would be great if I had an example I could apply to the other methods.如果我有一个可以应用于其他方法的示例,那就太好了。

Could you help me by writing the test method for this one?你能帮我写一个测试方法吗? It would be very useful.这将非常有用。

    @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);
    }

Thanks.谢谢。

You can use @Mock and @InjectMocks annotations.您可以使用@Mock@InjectMocks注释。 With it you can inject mocks to your controller.有了它,您可以将模拟注入您的 controller。

@Mock
PlayerService playerServiceMock;

And use when().then() from Mockito inside test or method with @Before annotation:并在带有@Before注释的测试或方法中使用 Mockito 中的when().then()

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

The same can be done for bundle.getString("put_player") . bundle.getString("put_player")也可以这样做。

Hoping you are using the Mockito.希望您使用的是 Mockito。 You can try the below code, need to add all imports您可以尝试以下代码,需要添加所有导入

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
public class YourClassNameTest {

    @Autowired
    MockMvc mockMvc;

    @InjectMocks
    YourClassName yourClassName;

    @Mock
    PlayerService playerService;

    @Before
    public void Setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(yourClassName);
    }

    @Test
    public void updatePlayerPasswordTest() throws Exception {

        PlayerEntity player = new PlayerEntity();
        // set some date if you want

        Mockito.when(playerService.updatePassword(anyString(), anyString())).thenReturn(player);

                RequestBuilder requestBuilder = MockMvcRequestBuilders
                .get("/player/update-password?token=abc&password=test")
                .accept(MediaType.APPLICATION_JSON);
        mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isCreated());      
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM