junit的test 方法执行两次

来源:互联网 发布:斗鱼主播qqq的淘宝店是 编辑:程序博客网 时间:2024/05/01 09:44

个人笔记

描述:在当前的junit class定义了一个方法,test,里面的逻辑是做一个数据库插入操作

结果:插入操作执行了2次

父类

@RunWith(SpringJUnit4ClassRunner.class)public abstract class AbstractTest {@Beforepublic void test() {MockitoAnnotations.initMocks(this);}}
执行逻辑的junit

@ContextConfiguration(locations = { "classpath*:demo.xml" })public class DaoTest extends AbstractTest{@ResourceDao dao;@Testpublic void test() {DaoModel model = new DaoModel();model.setUpdateTime(new Date());dao.saveObj(model);}}

debug的结果: 由于父类@Before方法和子类的@Test方法重名造成的。

分析:spring构造了org.junit.internal.runners.statements.RunBefores

流程

SpringJUnit4ClassRunner.withBefores ->
BlockJUnit4ClassRunner.withBefores ->
new RunBefores

public RunBefores(Statement next, List<FrameworkMethod> befores, Object target) {        this.next = next;        this.befores = befores;        this.target = target;}
它的befores就是AbstractTest,next是当前的DaoTest,target是model累

然后继续执行,

SpringJUnit4ClassRunner.runChild ->

org.junit.runners.model.FrameworkMethod的invokeExplosively方法

public Object invokeExplosively(final Object target, final Object... params)            throws Throwable {        return new ReflectiveCallable() {            @Override            protected Object runReflectiveCall() throws Throwable {                return method.invoke(target, params);            }        }.run();}
这时候method是AbstractTest的test方法,target是DaoTest类,则这时执行了一次DaoTest的test方法。


test方法执行完后,在进入RunBefores的evaluate方法,这时候的next是DaoTest,则导致了又执行了一次test方法。


so,更改父类的@Before方法名称。



0 0