Junit4小技巧-测试基类

来源:互联网 发布:word for mac如何使用 编辑:程序博客网 时间:2024/05/16 19:52

在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 testRun2017/03/22 00:23:25.945 WARN   24 testRun - write test run here2017/03/22 00:23:25.946 INFO   22 tearDown - ===End testRun
0 0
原创粉丝点击