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的evaluate方法,这时候的next是DaoTest,则导致了又执行了一次test方法。


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



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值