我目前正在为我的应用程序中的控制器编写一个JUnit测试用例,该用例返回一个对象(URL)。我试图断言期望和实际的URL是相同的。当我检查 MvcResult结果时,这里发生了两件事:
mockResponse 的状态码为200。
在 ModelAndView 中,模型确实具有预期的url值,但是当我尝试使用result.getResponse().getContentAsString()
声明结果时,
断言失败,因为结果为空。
我已经尝试过的方法:
在调试时,我看到控件移至服务,这意味着已正确模拟了值,并且预期的url返回了结果(如在检查时在ModelAndView中存在)。
我尝试将所需的URL作为json对象提供,使用对象映射器读取它,然后尝试使用JSONAssert,但结果仍然为空。
@RunWith(SpringJUnit4ClassRunner.class)
public class StudentControllerTest {
private static final String CACHE_URL= "cacheurl";
@Mock
StudentCacheService studentCacheService;
@InjectMocks
StudentCacheController studentCacheController;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(studentCacheController).build();
}
@Test
public void testGetScoresUrl() throws Exception {
Mockito.when(studentCacheService.getStudentUrl("123", "science"))
.thenReturn(new StudentUrl(CACHE_URL));
MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/123/scores")
.header("subject", "science").contentType(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful())
.andReturn();
Assert.assertEquals(CACHE_URL, result.getResponse().getContentAsString());
}
}
我的Controller类如下:
@Controller
@RequestMapping("/student")
public class StudentCacheController {
@Autowired
StudentCacheService studentCacheService;
@GetMapping(path = "/{studentId}/scores",produces = MediaType.APPLICATION_JSON_VALUE)
public StudentUrl getScores(@PathVariable String studentId, @RequestHeader(value = "subject", required = true) String subject) throws Exception {
return studentCacheService.getStudentUrl(studentId, subject);
}
}
响应如下:
MockHttpServletResponse:
Status = 200
Error message = null
Forwarded URL = student/123/scores
Included URL = []
ModelAndView:
model = ModelMap
key = studentUrl
value = StudentUrl
url = "cacheurl"
我收到此错误:org.junit.ComparisonFailure: expected:<[cacheurl]> but was:<[]>
任何帮助表示赞赏。谢谢!