您的位置:首页 > 编程语言 > Java开发

Spring Boot Test 学习

2018-03-13 11:28 344 查看
1. org.springframework.test.context.junit4.SpringRunner
    SpringRunner is an alias for the SpringJUnit4ClassRunner.To use this class, simply annotate a JUnit 4 based test class with {@code @RunWith(SpringRunner.class)}.

    
public final class SpringRunner extends SpringJUnit4ClassRunner {...}2. 创建Spring Boot测试类@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest{
@Autowired
        UserRepoistory repository;
       
        @Test
        public void testSomeCall(){
            //...           
        }
 }Tips: @SpringBootTest将会调用采用@SpringBootApplication声明的类去创建ApplicationContext.
3. 测试rest接口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.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class GreetingControllerTest {

@Autowired
private TestRestTemplate restTemplate;

@Test
public void hello() {
String body = this.restTemplate.getForObject("/hello", String.class);
assertThat(body).isEqualTo("Hello world!");
}
}Tips: 测试当前项目的rest接口时,不需要加项目名。比如当前项目名为greeting, rest路径为/hello, 直接访问
/hello就可以,不需要额外添加项目名/greeting.

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: