当前位置: 首页 > 知识库问答 >
问题:

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

松琦
2023-03-14
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)}

共有1个答案

汪正雅
2023-03-14

基于您的客户端类,希望建议以下更改,以使其更好地可测试:

    //  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 
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;
 类似资料:
  • 客户端测试更多关心客户端方面的代码执行情况,通常是web浏览器或者浏览器插件。区别于服务器端,代码在客户端执行并直接返回随后的结果。 下列文章描述了如何进行客户端的web应用测试: 基于DOM跨站脚本测试 (OTG-CLIENT-001) JavaScript脚本执行测试 (OTG-CLIENT-002) HTML注入测试 (OTG-CLIENT-003) 客户端URL重定向测试 (OTG-CLI

  • 如何在基于网络的 HTTP 客户端中重试 HTTP 请求? 请考虑以下处理程序,如果收到 HTTP 响应代码 503,它将尝试在 1 秒后重试 HTTP 请求: 在本例中,当我写入通道时,管道中的其他处理程序会看到HttpObjects,但实际上不会再次执行HttpRequest——只接收到一个HttpResponse。 我认为在这种情况下我只是滥用了 Channel,我需要创建一个新的通道(表示

  • 我在firefox web Browser中使用Rest Client add on。我想测试一个处理HTTP POST请求并使用JSON的web服务。我如何使用Rest Client测试它? 如果在请求正文中添加json,将得到一个*HTTP 415不受支持的媒体类型错误*。 这样做的正确方法是什么?

  • 我们实际上使用了JUnit和FakeSftpServerRule来测试我们定制的SFTP客户端。效果很好。 最后,我们希望摆脱junit,转而使用spock框架,因为我们试图迁移到groovy。 你们知道FakeSftpServerRule的等价物吗?或者,你们知道把junit规则“转换”成spock规则等价物的方法吗? 非常感谢。

  • 我正在测试一个Springmvc控制器,它得到一个网络服务客户端自动配带,它被嘲笑了。但是嘲笑并没有奏效。在测试返回中调用“验证(stuClient,乘以(1))”。获取所有学生(sAndP命令); 下面是我测试中的控制器方法: 下面是我的测试类:

  • 我必须向只通过表单数据(Mediatype.application_form_urlencoded)接受参数的服务器发布pojo。我知道jersey client可以将对象转换为xml、json和其他类型,但试图转换为APPLICATION_FORM_URLENCODED会出现异常,显示指定类型的body writer不可用。 是否有方法将对象序列化为application_form_urlenc