【发布时间】:2019-08-07 14:56:54
【问题描述】:
我想测试应该向“服务器”发送发布请求的发布方法(所以我想模拟来自服务器的响应并检查响应)。另外,我想测试响应在正文中是否包含 http 状态 OK。问题:我应该如何使用 mockito 来做到这一点?
我在客户端(客户端)中的发布方法:
public class Client{
public static void sendUser(){
String url = "http://localhost:8080/user/add";
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
User test = new User();
test.setName("test");
test.setEmail("a@hotmail.com");
test.setScore(205);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<User> request = new HttpEntity<>(test);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
if(response.getStatusCode() == HttpStatus.OK){
System.out.println("user response: OK");
}
}
}
另一个模块中的我的控制器(服务器端):
@RestController
@RequestMapping("/user")
public class UserController
{
@Autowired
private UserRepository userRepository;
@PostMapping("/add")
public ResponseEntity addUserToDb(@RequestBody User user) throws Exception
{
userRepository.save(user);
return ResponseEntity.ok(HttpStatus.OK);
}
测试:
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(classes = Client.class)
@AutoConfigureMockMvc
public class ClientTest
{
private MockRestServiceServer mockServer;
@Autowired
private RestTemplate restTemplate;
@Autowired
private MockMvc mockMvc;
@Before
public void configureRestMVC()
{
mockServer =
MockRestServiceServer.createServer(restTemplate);
}
@Test
public void testRquestUserAddObject() throws Exception
{
User user = new User("test", "mail", 2255);
Gson gson = new Gson();
String json = gson.toJson(user );
mockServer.expect(once(), requestTo("http://localhost:8080/user/add")).andRespond(withSuccess());
this.mockMvc.perform(post("http://localhost:8080/user/add")
.content(json)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().json(json));
}
}
现在我收到了这个错误:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ClientTest': Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.client.RestTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
【问题讨论】:
-
测试应该向服务器发送 post 请求的 post 方法,所以你想要一个真正的服务器调用而不是 mock ?
-
不,我想模拟响应
-
那么看起来不像 向服务器发送一个 post 请求,而是你想模拟一些 POST 请求的响应?对吗?
-
是的,我想模拟这个特定 POST 请求的 POST 响应
-
stackoverflow.com/questions/39486521/…、stackoverflow.com/questions/50271164/… 和 javased.com/?api=org.springframework.web.client.RestTemplate 这些是一些有用的链接..建议尝试一下,如果卡住了,请更新您的问题。
标签: java spring unit-testing post mockito