在web开发时进程遇到需要编写一些小的测试用例用于测试api接口是否可用,此时使用Spring框架的开发者大多会想到使用RestTemplate。本文实现一个使用RestTemplate发起GET请求,同事设置GET请求的http头的示例。
1、创建测试类的基类
创建一个测试类的基类BaseTester,用于导入测试类的配置文件,本例中配置文件使用的时java注解的config类。基类代码如下:
package api.landsem.tester.ram;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { EmptyConfiguration.class })
public class BaseTester {
}
2、创建配置类
上面创建的测试基类中导入了一个名为EmptyConfiguration的配置类,该配置类的代码如下:
package api.landsem.tester.ram;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EmptyConfiguration {
}
3、创建测试用例
测试用例向一个指定的api发起http请求,并设置post请求的参数,代码如下:
package api.landsem.tester.ram.api;
import java.util.Date;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import api.landsem.ram.factory.SignatureHelper;
import api.landsem.tester.ram.BaseTester;
import api.landsem.utils.LocalDateUtils;
import api.landsem.utils.TokenUtils;
public class CertificateRegistApiTester extends BaseTester{
private final static Logger logger = Logger.getLogger(CertificateRegistApiTester.class);
private final static String testKey = "LSadsfdslfm";
private final static String testSecret = "LSerkfdksvdsf";
private final static int intent = 101;
private final static String code = "2asfd5f69699532325686";
private final static String number = "665533255555";
private final static String salt = "10";
@Test
public void test() {
logger.info("call test.");
final String url = "http://192.168.1.245:8082/ram/ram/v1/certificates";
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("key", testKey);
map.add("intent", String.valueOf(intent));
map.add("number", number);
map.add("code", code);
map.add("signature", signature);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,null);
ResponseEntity<String> response = template.postForEntity( url, request , String.class );
logger.info("response="+response.getBody());
}
}