簡體   English   中英

用放心的 SpringBoot 斷言 boolean 響應

[英]Assert boolean response with restassured SpringBoot

I want to evaluate Boolean response coming from my Rest Controller in Spring Boot Junit Test Case. 響應似乎是相同的,但 Rest Assured 將括號放在響應值中。

我的 Controller:-

@PutMapping("/file/{id}")
ResponseEntity<Boolean> uploadFile(@RequestBody MultipartFile file,
        @PathVariable String id) {
        return new ResponseEntity<>(
                fileService.uploadImage(file, id),
                HttpStatus.CREATED);
    }

我的測試用例:-

@Test
    public void UploadAttachmentTest() throws Exception {
        given().pathParam("id", "randomId").multiPart(dummyFile).expect()
                .statusCode(HttpStatus.SC_CREATED).body(equalTo(true)).when()
                .put("/file/{id}");
    }

運行 junit 測試用例時出錯:-

java.lang.AssertionError: 1 expectation failed.
Response body doesn't match expectation.
Expected: <true>
  Actual: true

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:80)
    at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:74)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:59)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:237)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:249)
....

以您想要的格式提取響應。看起來像下面的代碼片段。

    @Test
    public void UploadAttachmentTest() throws Exception {
        Boolean response = given()
                          .pathParam("id", "randomId")
                          .multiPart(dummyFile)
                          .expect()
                          .statusCode(HttpStatus.SC_CREATED)
                          .extract().response().as(Boolean.class);

        // Here u can check response with assertTrue() or assertFalase()
        assertTrue(response);
    }

正確答案是

.statusCode(HttpStatus.SC_CREATED).body(is(true)).when()

所以使用equal使用is

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM