我有一个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;
}
以下是我的ControllerTest类代码段
@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,但它会变为0.因此,我的测试失败了。你能告诉我我错过了什么吗?
答案 0 :(得分:1)
我认为你可以代替写作
Mockito.when(leagueService.getResults(matchList)).thenReturn(leagueEntryList);
写
Mockito.when(leagueService.getResults(Mockito.anyList())).thenReturn(leagueEntryList);
如果这不起作用,我需要得到
的实现List<Match> listOfMatches = getListOfMatches();