【问题标题】:How to mock rest controller with ResponseEntity as return object?如何以 ResponseEntity 作为返回对象来模拟休息控制器?
【发布时间】:2023-03-14 01:50:01
【问题描述】:

我正在休息控制器中进行单元测试,这是返回:

return ResponseEntity.status(HttpStatus.OK).body(result);

我收到此错误:

Required request body is missing

这是我目前的测试:

def "Signup"() {
        given:
            UserDto userDto = new UserDto(id: 1, password: "password123",   username: "username123")
            def personDto = new PersonDto(id: 1, user : userDto)
        when: "signup url is hit"
            def response = mockMvc.perform(post('/person/signup'))
        then:
            personService.signup(userDto) >> personDto
            response.andExpect(status().isOk())
    }

知道如何模拟 .body 或如何在请求中添加正文。谢谢::)

【问题讨论】:

    标签: spring-mvc spock spring-mvc-test


    【解决方案1】:
    import static groovyx.net.http.ContentType.JSON
    
    import groovyx.net.http.RESTClient
    import groovy.util.slurpersupport.GPathResult
    import static groovyx.net.http.ContentType.URLENC
    
    
    def accountId = "yourAccountId" // this is the number after http://basecamp.com when logged into the basecamp website e.g. http://basecamp.com/1234567
    def userName = "basecampUserName"
    def password = "basecampPassword"
    
    def basecamp = new RESTClient( "https://basecamp.com/${accountId}/api/v1/".toString() )
    basecamp.auth.basic userName, password
    
    def response = basecamp.get(
                       path: "projects.json",
                       headers: ["User-Agent": "My basecamp application (myemail@domain.com)"]
                    )
    println response.data.toString(2) // or you can return this value and do whatever you want
    

    // 正文发帖

    def 'test post method'(){
     given:
     restClient .headers.Accept = 'application/json'
    
     when:
     def resp = restClient .post(path: 'path(ex:/api/list/',
     query:[param1:'param1value',param2:'param2value'],
     body: 'your json',
     contentType:'application/json'
     )
    
     then:
     resp.status == 200
    
     }
    }
    

    【讨论】:

      【解决方案2】:

      添加另一个期望,例如:

      response.andExpect(content().string(containsString('blah')))
      

      参考:

      MockMvcResultMatchers.content()

      ContentResultMatchers.string(org.hamcrest.Matcher<? super String> matcher)

      【讨论】:

        猜你喜欢
        • 2020-01-06
        • 1970-01-01
        • 2020-01-21
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2017-09-01
        • 1970-01-01
        • 2020-04-29
        相关资源
        最近更新 更多