Java-如何为RestTemplate postForObject编写Junit测试?

问题描述 投票:3回答:2

我在课堂上有2种方法。使用RestTemplate postForObject方法,我将JSON数据发布到端点。 getData是包含确定要发送哪些数据的逻辑的方法。从此方法中调用postMethod,其中包含包含RestTemplate postForObject方法的逻辑。这些方法是从另一种方法调用的,以(AAA-Arrange / Act / Assert)形式编写测试用例的最佳实践是什么,以便涵盖所有方法?我需要一些help/suggestions来为我的课程编写Junit测试

这是我的Java课堂



@Component
public class PlanRepo {
    private final RestTemplate restTemplate;
    private final String url;

    public PlanRepo(RestTemplate restTemplate, @mark("${message}") String url) {
        this.restTemplate = restTemplate;
        this.url = url;
    }

    public void startMethod(Set<Type> Types, String url) {
        Set<String> finalValue = new HashSet<>();
        checkType(Types, finalValue);
    }

    public void checkType(Set<Type> Types, Set<String> finalValue){
             finalValue = Types.stream()
                      .map(mark -> mark.getName())
                      .filter(mark ->a.getValue().equals(mark)||b.getValue().equals(mark)||c.getValue().equals(mark))
                       .map(language -> language.equals(c.getValue()) ? links : language)
                       .collect(Collectors.toSet());
                postJson(finalValue);
    }

    public Set<String> postJson(Set<String> finalValue){
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
            String oneString = String.join(",", finalValue);
           Map<String, String> requestBody = new HashMap<>();
            requestBody.put("type", oneString);
            requestBody.put("data", "aws");
            JSONObject jsonObject = new JSONObject(requestBody);
            HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), headers);
            MappingJackson2HttpMessageConverter jsonConvertor = new MappingJackson2HttpMessageConverter();
            restTemplate.getMessageConverters().add(jsonConvertor);
            StringHttpMessageConverter stringConvertor = new StringHttpMessageConverter();
            restTemplate.getMessageConverters().add(stringConvertor);
            String result = restTemplate.postForObject(url, request, String.class);
        } 
        return finalValue;
    }
} 

这里是Type类


     public class Type {

        private String selName;
        private Typemang mang;

        protected Type( String selName, Typemang mang ) {
            this.selName = selName;
            this.mang = mang;
        }
        public String getName() {
            return selName;
        }
        public Typemang getmang() {
            return mang;
        }
        @Override
        public String toString() {
            return getName();
        }

        @Override
        public int hashCode() {
            int hash = 12;
            hash = 31 * hash + getName().hashCode();
            return hash;
        }
@Override
        public boolean equals( Object obj ) {
            if( obj == null || !obj.getClass().equals( Type.class ) ) {
                return false;
            }

            Type view = (Type) obj;
            if( view.getName() != null && view.getName().equals( getName() ) ) {
                return true;
            }

            return false;
        }

    }

java unit-testing post junit resttemplate
2个回答
0
投票

前一段时间,我写了关于unit testing and test doubles的文章。您可以阅读如何进行单元测试的起点。

其中一些关键要点是:

  • 测试行为未实现。与实现细节无关的测试更易于维护。在大多数情况下,测试应着重于测试代码的公共API,并且无需对代码的实现细节进行测试。
  • 受测单元的大小是可自行决定的,但单元越小越好。
  • 谈论单元测试时,另一个典型的区别是被测单元应该是社交的还是单独的。
  • 替身替身是可以在测试中代表真实对象的对象,类似于特技替身替身电影中的演员的方式。他们是测试双打而不是模拟。模拟是测试双打之一。不同的测试双打有不同的用途。

0
投票

由于缺少许多信息,因此很难编写整个测试。例如。什么是Type。由于您没有发布课程的名称,因此暂时将其命名为MyClass。我也假设RestTemplate是通过类似

的构造函数注入的
MyClass(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
}

以下是使用JUnit 5Mockito进行单元测试的草案。我建议嘲笑RestTemplate。我必须承认,这样一来,我们将不会涵盖测试测试中MappingJackson2HttpMessageConverterStringHttpMessageConverter的用法。

所以非常原始的草稿可能看起来像这样

import java.util.ArrayList;
import java.util.Set;

import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;

class MyClassTest {

    private RestTemplate restTemplate;
    private MyClass myClass;

    @BeforeEach
    void setUp() {
        restTemplate = Mockito.mock(RestTemplate.class);
        myClass = new MyClass(restTemplate);
    }

    @Test
    void callMethod() {
        Set<Type> types = Set.of(/* one of your Types */);
        String url = "http://someUrl";
        String httpResult = "";

        Mockito.when(restTemplate.getMessageConverters()).thenReturn(new ArrayList<>());

        ArgumentCaptor<HttpEntity> request = ArgumentCaptor.forClass(HttpEntity.class);
        Mockito.when(restTemplate.postForObject(url, request.capture(), String.class)).thenReturn(httpResult);

        myClass.callMethod(types, url);

        HttpEntity<String> actualHttpEntity = request.getValue();
        Assert.assertEquals(actualHttpEntity.getBody(), "");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.