设为首页 加入收藏

TOP

junit的test 方法执行两次
2019-05-11 02:14:15 】 浏览:152
Tags:junit test 方法 执行

个人笔记

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

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

父类

@RunWith(SpringJUnit4ClassRunner.class)
public abstract class AbstractTest {

	@Before
	public void test() {
		MockitoAnnotations.initMocks(this);
	}
	
}
执行逻辑的junit

@ContextConfiguration(locations = { "classpath*:demo.xml" })
public class DaoTest extends AbstractTest{

	@Resource
	Dao dao;
	
	@Test
	public 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的eva luate方法,这时候的next是DaoTest,则导致了又执行了一次test方法。


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



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇ibatis数据源迁移(Oracle到MySQL.. 下一篇Zookeeper集群搭建

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目