gpt4 book ai didi

java - 使用 MockMvc 时主体为空

转载 作者:行者123 更新时间:2023-11-28 20:01:35 25 4
gpt4 key购买 nike

<pre><code>

@RunWith(SpringRunner.class)
@WebMvcTest(CustomerController.class)
public class CustomerControllerMvcTest {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@MockBean
private ICustomerService customerService;

@Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.dispatchOptions(true).build();
}

@Test
public void getTaskByUserdId1() throws Exception {
String expectedOutput = "{\"id\":3,\"name\":\"vikas\"}";
this.mockMvc.perform(MockMvcRequestBuilders.get("/customer/get/vikas")
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(content().string(expectedOutput));
}

@Test
public void getTaskByUserdId2() throws Exception {
String expectedOutput = "{\"id\":3,\"name\":\"vikas\"}";
this.mockMvc.perform(get("/customer/get/vikas"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString(expectedOutput)));
}
}

</code> </pre>

它总是给出空体:

<pre>
<code>

MockHttpServletRequest:

HTTP Method = GET
Request URI = /customer/get/vikas
Parameters = {}
Headers = {}

MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null Redirected URL = null
Cookies = []

</code>
</pre>

当我使用 TestRestTemplate 时它工作正常。但是,当我使用 MockMvc@MockBean 时,它总是给出空输出。我还使用了 com.gargoylesoftware.htmlunit.WebClient。可是,那也给了空虚的身躯。我不知道发生了什么。请帮忙。是版本问题还是我做错了什么?Spring Boot 版本:1.5.10

最佳答案

您的 Controller 执行 customerService 的方法。正确的?然后你必须 stub 该方法。

@Test
public void testMethod() throws Exception {
when(customerService.doSomething())
.thenReturn(mockResult); // you need to make this code

this.mockMvc.perform(get("/url"))
.andExpect(someThing);
}

关于java - 使用 MockMvc 时主体为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48546243/

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