我实际上创建了简单的Web服务,我想添加新的junit测试。 我有一种方法可以将人员添加到团队中。 这是我的方法(在休息控制器中):
@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
答案 0 :(得分:0)
doNothing()
仅用于void方法,如错误消息中所述,在您的情况下,您必须使用以下内容:
when(teamService.createTeam(teamDto)).thenReturn(Reponse.ok().build());
注意:您必须覆盖@equals
类
TeamDto
方法
答案 1 :(得分:0)
根据错误,我猜TeamService.createTeam
或PersonService.addPerson
没有void
返回类型,您只能对方法进行模拟doNothing
行为,返回{{ 1}}。此外,您在void
字段上缺少@Mock
注释。
在春季启动测试中,最好使用@MockBean注释。对于控制器测试,最好使用@WebMvcTest,然后您可以跳过在设置方法中完成的配置:)
答案 2 :(得分:0)
@InjectMocks
Controller controllerMock;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controllerMock).build();
}
其中-ControllerMock将是Controller类的Mock