在 四、spring boot +mybatis(通过properties配置) 集成 博客中,我已经集成了mybatis,今天这篇博客主要是简单讲解下怎么集成junit。
我看了网上很多帖子都是说的使用@WebIntegrationTest进行接口相关的junit测试,但是我发现在springboot 1.5版本后已经没有这个注解了。
我这边查阅了一些资料,最后采用了注解TestRestTemplate
TestRestTemplate 类是sprigboot专门用作接口调用的类,再测试时无需启动容器,并且带有get、post、put、delete相关方法
我在这里只贴出junit测试类代码,工程代码已上传到码云。
https://gitee.com/yangok/springboot_junit.git
TestUserController
package springbootDemo.junit.app;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import com.yang.springbootDemo.controller.ApplicationMain;
import com.yang.springbootDemo.entity.UserEntity;
/**
*
* @author liuyang
*
* 2018年8月3日 上午10:21:37
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationMain.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestUserController {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void getUserTest() throws Exception {
String name = "admin";
Map<String,String> multiValueMap = new HashMap<>();
//传值,但要在url上配置相应的参数
multiValueMap.put("name",name);
UserEntity resultUser = testRestTemplate.getForObject("/user/getUser?name={name}", UserEntity.class,multiValueMap);
Assert.assertNotNull(resultUser);
Assert.assertEquals(name, resultUser.getName());
}
}