JUnit4的简单使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_23179075/article/details/78549806

之前做Android开发,因为涉及到UI和Android本身的Activity的生命周期影响,项目的测试全是整个项目一起跑起来测试,所以很少写测试类。渐渐的快忘了Junit这个东西的存在。

最近在学习Spring框架使用,决定把Junit4这个单元测试工具用起来。记录下使用方法。(只代表个人使用习惯)

略过集成Junit4步骤。

以测试Spring框架为例
创建一个BaseJUnit4Test类

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
/**
 * date   : 2017/11/15 17:24
 * author : zhengliang
 */
@RunWith(BlockJUnit4ClassRunner.class)
public abstract class BaseJUnit4Test {
    public BaseJUnit4Test() {
    }

   /**
    * Test执行之前调用,可以做一些初始化操作。
    */
    @Before
    public void before(){
        ...
    }

   /**
    * Test执行完成后调用,可以做一些回收和销毁操作。
    */
    @After
    public void after(){
        ...
    }

   /**
    * 具体的测试方法
    */
    @Test
    public abstract void test();
}

具体使用流程

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

/**
 * date   : 2017/11/15 17:24
 * author : zhengliang
 */
@RunWith(BlockJUnit4ClassRunner.class)
public abstract class BaseJUnit4Test {
    /**
     * Spring容器上下文
     */
    private ClassPathXmlApplicationContext context;
    /**
     * Spring配置文件路径
     */
    private String springXmlPath;

    public BaseJUnit4Test() {
    }

    public BaseJUnit4Test(String springXmlPath) {
        this.springXmlPath = springXmlPath;
    }
    @Before
    public void before(){
        //如果地址为空 设置默认值
        if (StringUtils.isEmpty(springXmlPath)) {
            springXmlPath = "classpath*:spring-*.xml";
        }
        context = new ClassPathXmlApplicationContext(springXmlPath);
        context.start();
    }

    @After
    public void after(){
        context.destroy();
    }

    @Test
    public abstract void test();

    protected <T extends Object> T getBean(String beanId){
        return (T) context.getBean(beanId);
    }

    protected <T extends Object> T getbean(Class<T> clazz){
        return context.getBean(clazz);
    }

}

实现的测试类

import com.sie.bunny.base.BaseJUnit4Test;

/**
 * date   : 2017/11/16 11:39
 * author : zhengliang
 */
public class TextEditorTest extends BaseJUnit4Test {
    public TextEditorTest (){
        super("classpath*:spring-dependency-injection.xml");
    }

     public void test() {
        TextEditor textEditor = super.getBean("textEditor");
        textEditor.spellChecker();
    }

}

猜你喜欢

转载自blog.csdn.net/qq_23179075/article/details/78549806