我有一个RestController,它只有一种用于HTTP GET的方法,并且没有输入参数。它调用了需要一些参数的服务方法。以下是控制器片段。
@RequestMapping(value = "/leagueResults", method = RequestMethod.GET)
public List<LeagueTableEntry> getResults(){
List<LeagueTableEntry> leagueTableEntryList = new ArrayList<>();
List<Match> listOfMatches = getListOfMatches();
leagueTableEntryList = leagueService.getResults(listOfMatches);
return leagueTableEntryList;
}
下面是我的ControlerTest类摘要
@RunWith(SpringRunner.class)
@WebMvcTest(LeagueController.class)
@WebAppConfiguration
public class LeagueControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private LeagueService leagueService ;
private List<LeagueTableEntry> leagueEntryList;
private List<Match> matchList;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
createSampleInputData();//This method populates the instance variable matchList
getLeagueEntryOutput();//This method populates the instance variable leagueEntryList
}
@Test
public void checkNoOfRecordsReturned()throws Exception {
try{
Mockito.when(leagueService.getResults(matchList)).thenReturn(leagueEntryList);
mvc.perform(get("/leagueResults").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(4)));
}
catch(Exception e){
throw new Exception();
}
}
private void getLeagueEntryOutput(){
leagueEntryList = new ArrayList<>();
leagueEntryList.add(new LeagueTableEntry());
leagueEntryList.add(new LeagueTableEntry());
leagueEntryList.add(new LeagueTableEntry());
leagueEntryList.add(new LeagueTableEntry());
}
所以,在这里,我期望返回列表中的对象计数为4,但它的测试失败了。你能让我知道我想念什么。
我认为你可以写
Mockito.when(leagueService.getResults(matchList)).thenReturn(leagueEntryList);
写
Mockito.when(leagueService.getResults(Mockito.anyList())).thenReturn(leagueEntryList);
另外,如果这不起作用,我需要实现
List<Match> listOfMatches = getListOfMatches();