为spring-hateoas执行单元测试用例时缺少jsonRootName



我已经使用spring-boot-starter Hateoas开发了一个rest服务,并且我能够正确地获得json输出,如下所示:

"_embedded": {
   "bills": 
         {
          uid: "123"
          code: "0000"

并且我需要使用mockito来编写相同的单元测试用例。我写的代码如下。

ApplicationTest.java:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class ApplicationTest {

BillControllerAutoTest:

public class BillControllerAutoTest {
private BillService mockBillService;
private MockMvc mockMvc;
private static final String BILL_UID = "99991";
@Before
public void setupController() {
           mockBillService= mock(BillService .class);
          BillController controller = new BillController (mockBillService);
    mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}    
@Test
public void testGetBills() throws Exception {
    // some fake data
    final List<Bill> fakeBillList= new ArrayList<>();
    fakeBillList.add(BillFake.bill("1234"));
    when(mockBillService.getBills(BILL_UID))
            .thenReturn(fakeBillList.stream());
    // execute and verify
    mockMvc.perform(get("/bills/" + BILL_UID ))
            .andExpect(content().string(containsString(""embedded":{"bills"")))

BillController.java:

@RestController
@RequestMapping(value = "/bills/{billUid}", produces = "application/hal+json")
public class BillController extends BaseController {
private BillService billService;
    @RequestMapping(method = RequestMethod.GET, value = "")
public ResponseEntity<Resources<Resource<Bill>>> getBills(@PathVariable String billUid) {
    return resourceListResponseEntity(
            () -> billService.getBills(billUid),
            bill-> createResource(billUid),
            resources -> resources.add(linkTo(methodOn(BillController .class)
                    .getBills(billUid)).withSelfRel()));
}

依赖项:

dependencies {
compile "org.springframework.boot:spring-boot-starter-hateoas"
compile "org.springframework.boot:spring-boot-starter-ws"
compile "org.springframework.boot:spring-boot-starter-actuator"
testCompile("org.springframework.boot:spring-boot-starter-test")
} 

我的构建失败,出现以下堆栈跟踪:

java.lang.AssertionError: Response content
Expected: a string containing ""_embedded":{"bills""
 but: was 
"content":[
   {
   uid: "123"
   code: "0000"

这意味着单元测试的mockMvc返回的响应中没有"_embedded:{bills"。我是否缺少任何配置,请告诉我。如果有任何帮助,我们将不胜感激。

我在这里回答了非常相似的问题:Spring';s MockMVC响应Don';t匹配浏览器响应

简而言之:springHATEOAS添加了用于正确渲染hal的额外配置(如下所述:http://docs.spring.io/spring-hateoas/docs/0.19.0.RELEASE/reference/html/#configuration)。在测试中,您必须手动应用此配置。查看第一个链接以了解如何做到这一点的详细信息

相关内容

  • 没有找到相关文章

最新更新