SpringBoot测试用例模板

Service接口测试

@RunWith(SpringJUnit4ClassRunner.class)
//指定SpringBoot工程的Application启动类
//支持web项目
@WebAppConfiguration
@SpringBootTest(classes = AppApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class IndexControllerTest {
    @Autowired
    private IndexService indexService;

    @Test
    public void indexServiceTest() {
        String body = indexService.getStr();
        assertThat(body).isEqualTo("ok");
    }
}

这个是一个简单的Service测试,也是最开发中最常用的测试方式,直接注入Service调用方法能够获取到放回的内容,并且校验内容是否正确,`@SpringBootTest`提供了如下webEnvironment配置

Rest 接口测试

@RunWith(SpringRunner.class)
    @SpringBootTest(classes = AppApplication.class,
            webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class IndexControllerTest {
        @Autowired
        private TestRestTemplate restTemplate;
        //注入端口号
        @LocalServerPort
        private int port;
        @Test
        public void indexControllerTest() {
            String body = this.restTemplate.getForObject("/index", String.class);
            assertThat(body).isEqualTo("ok"+port);
        }
    }

<div class="se-preview-section-delimiter"></div>

日志捕获测试

 @RunWith(SpringJUnit4ClassRunner.class)
    //指定SpringBoot工程的Application启动类
    //支持web项目
    @WebAppConfiguration
    @SpringBootTest(classes = AppApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
    public class OutputCaptureTest {
        private Log log = LogFactory.getLog(OutputCaptureTest.class);
        @Rule
        // 这里注意,使用@Rule注解必须要用public
        public OutputCapture capture = new OutputCapture();

        @Test
        public void testLogger() {
            System.out.println("sd");
            log.info("test");
            assertThat(capture.toString(), Matchers.containsString("test"));
        }

        @Test
        public void testSdLogger() {
            System.out.println("sd");
            assertThat(capture.toString(), Matchers.containsString("sd"));
        }

        @Test
        public void testNoSdLogger() {
            System.out.println("sd");
            assertThat(capture.toString(), Matchers.containsString("nod"));
        }
    }

 

posted @ 2018-04-28 14:32  Aick  阅读(298)  评论(0编辑  收藏  举报