gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:10 24 4
gpt4 key购买 nike

我使用 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 {

BillController自动测试:

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")
}

我的构建失败并出现以下 stackTrace:

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

这意味着“_embedded : { bills”在单元测试的mockMvc返回的响应中不可用。我是否缺少任何配置,请告诉我。任何帮助将不胜感激。

最佳答案

我在这里回答了非常类似的问题:Spring's MockMVC Responses Don't Match Browser Response

简而言之:spring HATEOAS 添加了用于正确渲染 hal 的附加配置(如下所述: http://docs.spring.io/spring-hateoas/docs/0.19.0.RELEASE/reference/html/#configuration )。在您的测试中,您必须手动应用此配置。检查第一个链接以获取有关如何操作的详细信息

关于java - 为 spring hatoas 执行单元测试用例时缺少 jsonRootName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29488161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com