简体   繁体   中英

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. 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. With it you can inject mocks to your controller.

@Mock
PlayerService playerServiceMock;

And use when().then() from Mockito inside test or method with @Before annotation:

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

The same can be done for bundle.getString("put_player") .

Hoping you are using the 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());      
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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