配置:右键要加入单元测试的工程,选择properties,然后选择java build path,选择add library,选择junit即可。

编写:右键要测试的class,new一个junit test case,更改其source folder,next之后可选择要测试的class中的要测试的方法,则可自动生成。

运行:右键要运行单元测试的class,选择junit即可。

测试套件测试:

1.测试套件就是组织测试类一起运行的。

2.写一个作为测试套件的入口类,这个类里不包含其他的方法,更改测试运行器Suite.class,将要测试的类作为数组传入到Suite.SuiteClasses({}),即如下图:

junit单元测试+junit与Spring结合

参数化设置测试:

1.更改默认的测试运行器为@RunWith(Parameterized.class)

2.声明变量来存放预期值和结果值

3.声明一个返回值为Collection的公共静态方法,并使用@Parameters进行修饰

4.为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值。示例代码如下图:

junit单元测试+junit与Spring结合

注意:

1.单元测试代码最好与业务代码分开,对于每一个要测试的class,所生成的单元测试的class,两者包名要保持一致。

2.测试方法必须用@Test进行修饰。

3.测试方法必须使用public void进行修饰,不能带任何参数。

4.测试单元中的每个方法必须可以独立测试,测试方法间不能有任何的依赖。

5.测试类最好使用Test作为类名的后缀。

6.测试方法最好使用test作为方法名的前缀。

流程点:

1.@BeforeClass修饰的方法会在所有方法被调用前被执行,而且该方法时静态的,所以当测试类被加载后接着就会运行它,而且在内存中它只会存在一份实例,它比较适合加载配置文件。

2.@AfterClass所修饰的方法通常用来对资源的清理,如关闭数据库的链接。

3.@Before和@After会在每个测试方法的前后各执行一次。

4.@Ignore所修饰的测试方法会被测试运行器忽略。

5.@RunWith可以更改测试运行器

 

 

 

junit单元测试+junit与Spring结合

UnitTestBase的写入:

 1 public class UnitTestBase {
 2     private ClassPathXmlApplicationContext context;
 3     private String springXmlpath;
 4     public UnitTestBase() {};
 5     
 6     public UnitTestBase(String springXmlpath) {
 7         this.springXmlpath = springXmlpath;
 8     }
 9     
10     @Before
11     public void before() {
12         if(StringUtils.isEmpty(springXmlpath)) {
13             springXmlpath = "classpath*:spring-*.xml";//配置文件路径通过构造函数传入,
14         }
15         try {
16             context = new ClassPathXmlApplicationContext(springXmlpath.split("[,\\s]+"));//创建spring的容器context
17             context.start();//启动后查找配置文件里面配置的信息,并解析这些文件,然后装载到spring的上下文,即context里,
18         } catch(BeansException e) {
19             e.printStackTrace();
20         }
21     }
22     
23     @After
24     public void after() {
25         context.destroy();
26     }
27     
28     @SuppressWarnings("unchecked")
29     protected <T extends Object> T getBean(String beanId) {
30         return (T)context.getBean(beanId);//通过getBean方法获取相应的对象,而这里的beanId即是子类中传入的oneInterface,也在spring-ioc.xml文件中配置过的bean
31     }
32     
33     protected <T extends Object> T getBean(Class<T> clazz) {
34         return context.getBean(clazz);
35     }
36     
37 }
View Code

相关文章:

  • 2022-12-23
  • 2021-08-11
  • 2021-11-17
  • 2021-06-05
  • 2021-06-08
  • 2021-11-26
猜你喜欢
  • 2021-10-07
  • 2021-10-20
  • 2021-04-20
  • 2022-12-23
  • 2022-12-23
  • 2021-12-04
  • 2021-07-27
相关资源
相似解决方案