在项目中,经常会需要测试程序中的某个功能或者某个方法,来判断程序的正确性和性能。如何在spring boot项目中完成单元测试呢。
首先,需要有必备的工具包。spring-boot测试工具包
第二步,导入相关的注解。@RunWith(SpringRunner.class)@SpringBootTest(classes = SkynetApplication.class)@EnableAutoConfiguration @RunWith就是一个运行器,可以指定用哪个测试框架运行,@RunWith(JUnit4.class)就是指用JUnit4来运行@RunWith(SpringJUnit4ClassRunner.class)使用了Spring的SpringJUnit4ClassRunner,以便在测试开始的时候自动创建Spring的应用上下文。其他的想创建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[]{"克","明","发","代发","犯的",
"和","我","人","同","娟","娟娟","丽","美丽","利","陆"
,"空间","改","办法","航空",
"留","泰","晨光","长城","层层","莉莉","胡霍","娜娜","大","光荣"};
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[]{"克","明","发","代发","犯的",
"和","我","人","同","娟","娟娟","丽","美丽","利","陆"
,"空间","改","办法","航空",
"留","泰","晨光","长城","层层","莉莉","胡霍","娜娜","大","光荣"};
returnf[random.nextInt(f.length-1)]+s[random.nextInt(s.length-1)];
}
}
第三,在需要测试的方法中添加@Test方法运行即可。