Java测试类相关
时常我们需要测试类进行测试项目的功能代码,
一,Java的 springboot 测试类编写,注意类前加@RunWith()和@SpringBootTest(),测试类相关的写法,简要编写如下,
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(class=启动类.class)
或者
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = 启动类.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
二,测试类中各个测试方法根据需要加 @Before (初始化相关),@Test (测试方法)等注解
一个完整例子如下:
package com.xxx.springBoot01.test;
import org.junit.Before;
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.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import com.xxx.springBoot01.SpringBoot01App; //启动类
import com.xxx.springBoot01.service.MyService;
//@RunWith(SpringJUnit4ClassRunner.class) //ok
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBoot01App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExcelServiceImplTest {
@Autowired
private MyService myService;
@Before
public void createFun01Test() throws Exception {
//...more code here...
System.out.println("before test fun do... ");
}
//测试方法01
@Test
public void createFun01Test() throws Exception {
//...more code here...
System.out.println("test func01 ");
}
//测试方法
@Test
public void createUserCostCountExcelFileTest() throws Exception {
//...more code here...
System.out.println("test func02 ");
}
}
简单例子,欢迎拍砖留言讨论...