java - 单元测试用例 MockRestServiceServer 预期的 url 不适用于 RestTemplate

标签 java spring rest unit-testing

我已经测试了一个验证 url 的 url 类

class ValidateUrl {
    public Integer validateUrl(String url, int timeOut) throws Exception {
        String url;
        private RestTemplate restTemplate = new RestTemplate();
        try {
            ((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setConnectTimeout(1000 * timeOut);
            ResultClass result = restTemplate.postForObject(url, null, ResultClass.class);
            if(result!= null) {
                return result.getErrorCode();
            }

        } catch (Exception e) {
            log.error("Error"+ e);
        }
        return -1;

    }
}

我已经创建了一个测试类的测试用例 ValidateUrlTest 我正在验证 url

@Autowire
private ValidateUrl validateUrlInstance

private String url = "https://testingurl.com";
private String result = "{\"result\" : \"-1\"}";

@Test
public void validateUrlTest() throws Exception{
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    RestTemplate template = new RestTemplate(factory);
    MockRestServiceServer server = MockRestServiceServer.createServer(template);
    server.expect(requestTo(url))
            .andRespond(given());
    int i= validateUrlInstance.validateUrl(url, 2);
    server.verify();

}

但是得到 java.lang.AssertionError:需要进一步的请求 [testng] 1 中的 0 被执行

最佳答案

您正在模拟的 RestTemplate 实例不是 ValidateUrl 类中使用的实例。

您应该注入(inject)它,而不是直接在方法中实例化它。

public class ValidateUrl {

    private RestTemplate restTemplate;

    @Autowired
    public ValidateUrl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public Integer validateUrl(String url, int timeOut) throws Exception {
     ...
    }
}

关于java - 单元测试用例 MockRestServiceServer 预期的 url 不适用于 RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846912/

相关文章:

java - 我正在开发在后台服务上运行音乐的音乐播放器应用程序,当我离开该应用程序时,媒体播放器停止

java - 方法 枚举 isBigger()

Java端点层

java - JPA 实体是否存储对实体管理器的引用?

java - 在 Java 中使用弱引用的成本

java - 如何在 Spring MVC 和 Hibernate 中将对象列表转换为 JSON?

java - Spring REST Controller 部分更新现有资源

json - 如何在 wso2 esb 的 json 正文中传递 & 号

java - JsonGetter 给出空值

java - Spring Boot 2.1 中热重载 Thymeleaf 模板和资源包