天天看点

Junit4小技巧-测试基类

在Junit4使用的时候,直接运行,通过控制台输出来进行问题判断,,这比启用debug模式更加迅速,但有时需要知道哪个方法开始输出,如果每次都在方法开始时,打印方法名称,那是较麻烦的事情。

通过测试基类,通过rule,可以带来一个方便,测试基类代码如下

package kata.testassist;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;

public abstract class BaseTest {
 protected static final Logger logger =  LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    @Rule
    public TestName name = new TestName();

    @Before
    public void init() {
        logger.info("===Start " + name.getMethodName());
    }

    @After
    public void tearDown() throws Exception {
        logger.info("===End " + name.getMethodName());
    }
}
           

实际的测试类继承自测试基类,样例如下

package kata.testassist;

import static org.junit.Assert.*;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class BaseTestTest extends BaseTest {
    @Test
    public final void testRun() {
        logger.warn("write test run here");
    }
}
           

运行输出结果如下:

2017/03/22 00:23:25.943 INFO   17 init - ===Start testRun
// :: WARN    testRun - write test run here
// :: INFO    tearDown - ===End testRun