2015-04-07 79 views
1

我一直在使用彈簧引導起動HATEOAS開發的REST服務,我能正常得到JSON輸出,如下圖所示:jsonRootName丟失而執行單元測試用例春天HATEOAS

"_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" 

這意味着「_embedded:{法案」不可通過單元測試的mockMvc返回的響應。我是否錯過了任何配置,請讓我知道。任何幫助將不勝感激。

回答