I want to test the post method that should send a post request to "server" (So I want to mock the response from the server and check the response). Also, I want to test that the response contains http status OK in the body. Question: How should I do that with mockito?
My Post Method in the client (Client-side):
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");
}
}
}
My Controller in another module (server-side):
@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);
}
Test:
@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));
}
}
And now i am getting this error:
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)}