gpt4 book ai didi

java - 使用模拟休息 Controller 方法进行 Junit 测试

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:33 24 4
gpt4 key购买 nike

我实际上有一个创建简单的网络服务,我想添加新的 junit 测试。我有一种将人员添加到团队中的方法。这是我的方法(在休息 Controller 中):

@PostMapping("/addPeopleToTeams/{teamId}/{personId}")
@ResponseBody
public ResponseEntity<?> addPeopleToTeam(@PathVariable Long teamId, @PathVariable Long personId) {
TeamsAndPersonsId teamsAndPersonsId = new TeamsAndPersonsId(personId, teamId);
teamService.findTeamById(teamsAndPersonsId.getTeamId());
personService.findById(teamsAndPersonsId.getPersonId());
teamService.addPersonsToTeams(personId, teamId);
return ResponseEntity.ok(teamsAndPersonsId);

}

对于这个方法,我想编写一个 Junit 测试,但出了问题:/这是我的测试类,方法如下:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TeamControllerTest {

private ObjectMapper mappingObject = new ObjectMapper();
private MockMvc mockMvc;
@Mock
private TeamService teamService;
private PersonService personService;

@Before
public void initTest() {
mockMvc = MockMvcBuilders
.standaloneSetup(new TeamController(teamService, personService))
.setControllerAdvice(GlobalExceptionHandler.class)
.build();
}
@Test
public void shouldAddPersonToTeam() throws Exception{
TeamDto teamDto = prepareTeamDto();
PersonDto personDto = new PersonDto(1L, "Bob", "Noob", "mail@first.pl", "Warszawa", "APPS", "Developer");
doNothing().when(teamService).createTeam(teamDto);
doNothing().when(personService).addPerson(personDto);

mockMvc.perform(post("/addPeopleToTeams/{teamId}/{personId}",1,1))

.andExpect(status().isOk());

}

private TeamDto prepareTeamDto() {
return new TeamDto(1L, "Jan", "local", "wawa", 6);
}

实际上对于这个方法我有这个错误:

org.mockito.exceptions.base.MockitoException: 
Only void methods can doNothing()!
Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
Above means:
someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called

最佳答案

doNothing() 仅用于 void 方法,如错误消息中所述,在您的情况下,您必须使用类似以下内容的内容:

when(teamService.createTeam(teamDto)).thenReturn(Reponse.ok().build());

注意:您必须重写 TeamDto 类中的 @equals 方法

关于java - 使用模拟休息 Controller 方法进行 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817755/

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