????? 在項目中乳绕,經(jīng)常會需要測試程序中的某個功能或者某個方法,來判斷程序的正確性和性能逼纸。如何在spring boot項目中完成單元測試呢洋措。
? ? ? 首先,需要有必備的工具包杰刽。spring-boot測試工具包<dependency<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency>此包中有很多的測試包菠发。
????? 第二步,導入相關(guān)的注解贺嫂。@RunWith(SpringRunner.class)@SpringBootTest(classes = SkynetApplication.class)@EnableAutoConfiguration? @RunWith就是一個運行器滓鸠,可以指定用哪個測試框架運行,@RunWith(JUnit4.class)就是指用JUnit4來運行@RunWith(SpringJUnit4ClassRunner.class)使用了Spring的SpringJUnit4ClassRunner第喳,以便在測試開始的時候自動創(chuàng)建Spring的應(yīng)用上下文糜俗。其他的想創(chuàng)建spring容器的話,就得子啊web.xml配置classloder曲饱。 注解了@RunWith就可以直接使用spring容器悠抹,直接使用@Test注解,不用啟動spring容器扩淀;這里springboot選擇的是@RunWith(SpringRunner.class)楔敌;@SpringBootTest(classes = SkynetApplication.class)用來指定配置;@EnableAutoConfiguration是的程序的配置可以自動的注入容器中引矩。代碼如下:
/**
*@author:kewei.zhang
*@Date:2017/11/28
*@Time:下午3:03
* Description:
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SkynetApplication.class)
@EnableAutoConfiguration
public classTestIndex {
@Autowired
privateTbTestMappertbTestMapper;
@Test
public voidtestInsert(){
TbTest tbTest =newTbTest();
tbTest.setAge(1);
tbTest.setBrithday(newDate());
tbTest.setHigh(172);
tbTest.setIsboy((short)1);
tbTest.setName("張克巍");
tbTest.setSchool("皖西學院");
tbTest.setWigth(158);
tbTestMapper.insertSelective(tbTest);
}
@Test
public voidtestInsertMany()throwsException{
String[] f =newString[]{"張","王","周","武","李",
"胡","趙","陳","苗","戴","習","毛","朱","韓","陸"};
String[] s =newString[]{"克","明","發(fā)","代發(fā)","犯的",
"和","我","人","同","娟","娟娟","麗","美麗","利","陸"
,"空間","改","辦法","航空",
"留","泰","晨光","長城","層層","莉莉","胡霍","娜娜","大","光榮"};
TbTest tbTest =newTbTest();
Random random =newRandom();
longc = System.currentTimeMillis();
for(inti =0; i <10000; i++){
tbTest.setAge(random.nextInt(100));
tbTest.setBrithday(DateUtil.parseDate(random.nextInt(2017)+"-"+random.nextInt(12)
+"-"+random.nextInt(30)+" "+random.nextInt(24)+":"+random.nextInt(60)+":"+random.nextInt(60),"yyyy-MM-dd HH:mm:ss"));
tbTest.setHigh(random.nextInt(200));
tbTest.setIsboy((short)random.nextInt(2));
tbTest.setName(f[random.nextInt(f.length-1)]+s[random.nextInt(s.length-1)]);
tbTest.setSchool("皖西學院"+random.nextInt(10000));
tbTest.setWigth(random.nextInt(200));
tbTestMapper.insertSelective(tbTest);
}
System.out.println("耗時:"+(System.currentTimeMillis()-c)/1000);
}
publicString getName(){
Random random =newRandom(100);
String name;
String[] f =newString[]{"張","王","周","武","李",
"胡","趙","陳","苗","戴","習","毛","朱","韓","陸"};
String[] s =newString[]{"克","明","發(fā)","代發(fā)","犯的",
"和","我","人","同","娟","娟娟","麗","美麗","利","陸"
,"空間","改","辦法","航空",
"留","泰","晨光","長城","層層","莉莉","胡霍","娜娜","大","光榮"};
returnf[random.nextInt(f.length-1)]+s[random.nextInt(s.length-1)];
}
}
第三梁丘,在需要測試的方法中添加@Test方法運行即可侵浸。