gpt4 book ai didi

java - 使用 Mockito 在客户端测试 POST 请求

转载 作者:行者123 更新时间:2023-11-29 04:10:56 24 4
gpt4 key购买 nike

我想测试应该向“服务器”发送发布请求的发布方法(所以我想模拟来自服务器的响应并检查响应)。另外,我想测试响应正文中是否包含 http 状态 OK。问题:我应该如何使用 mockito 做到这一点?

客户端(客户端)中的我的 Post 方法:

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");
}

}
}

另一个模块(服务器端)中的我的 Controller :

@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)}

最佳答案

根据您的 Client 类,建议进行以下更改以使其更易于测试:

    //  class
public class Client {

/*** restTemplate unique instance for every unique HTTP server. ***/
@Autowired
RestTemplate restTemplate;

public ResponseEntity<String> 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);

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");
}
return response;
}
}

然后对于上面我们 Junit 作为:

@RunWith(MockitoJUnitRunner.class)
public class ClientTest {

private String RESULT = "Assert result";

@Mock
private RestTemplate restTemplate;

@InjectMocks
private Client client;

/**
* any setting needed before load of test class
*/
@Before
public void setUp() {
// not needed as of now
}

// testing an exception scenario
@Test(expected = RestClientException.class)
public void testSendUserForExceptionScenario() throws RestClientException {

doThrow(RestClientException.class).when(restTemplate)
.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), any(Class.class));
// expect RestClientException
client.sendUser();
}

@Test
public void testSendUserForValidScenario() throws RestClientException {

// creating expected response
User user= new User("name", "mail", 6609);
Gson gson = new Gson();
String json = gson.toJson(user);
doReturn(new ResponseEntity<String>(json, HttpStatus.OK)).when(restTemplate)
.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), any(Class.class));
// expect proper response
ResponseEntity<String> response =
(ResponseEntity<String>) client.sendUser();
assertEquals(this.RESULT, HttpStatus.OK, response.getStatusCode());
}
}

基本上在您的 sendResponse() 函数中,我们这样做:

// we are getting URL , creating requestHeader
// finally creating HttpEntity<User> request
// and then passing them restTemplate.exchange
// and then restTemplate is doing its job to make a HTPP connection and getresponse...
// and then we are prinnting the response... somestuff

因此在相应的测试中我们也应该只测试函数在做什么由于连接由 restTemplate 负责,并且您没有覆盖 restTemplate 的任何工作,因此我们不应该为此做任何事情......而只是测试我们的代码/逻辑。

最后,要确保导入看起来像:

可以肯定的是,导入会像:

import org.springframework.http.HttpEntity; 
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

希望这对您有所帮助。

关于java - 使用 Mockito 在客户端测试 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201060/

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