具有Path变量和Object

时间:2017-07-03 20:49:05

标签: unit-testing junit

我有如下控制器:

@RestController
@RequestMapping("/v1/controller")
public class FindValue {

@RequestMapping(path="{id}/Method", method = POST)
    public ResponseEntity<HttpStatus> setMethodValue (@PathVariable Integer id, @RequestBody FindRequest findRequest) {

如何使用mockMvc从Junit调用此方法

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(MockitoJUnitRunner.class)
public class FindValue {
    @InjectMocks
    private FindValue mockFindValue;

    private MockMvc mockMvc;

    @Test
    public void testMethodValue() throws Exception {
        FindRequest findRequest = new FindRequest();
        findRequest.setValue("thevalue");

        mockMvc
            .perform(post("/v1/controller/{id}/Method", 1)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json;charset=utf-8")
            .content(asJsonString(findRequest))
            ).andExpect(status().isCreated());

    }

但是这会返回404错误

有人可以帮忙吗

1 个答案:

答案 0 :(得分:0)

您拥有控制器 / v1 / controller 的root reuqest映射,以及资源&#34; {id} / Method &#34;

的映射

它测试你创建未映射的url: &#34;的 / V1 /控制器/ {ID} /方法&#34;

我认为应该是

@RequestMapping(path="/{id}/Method", method = POST)

和@JB Nizet +1