Jmockit: Mock父类中的protected方法/变量

近些日子写Junit测试比较多,接触Jmockit也有几个月了,但是都是间或用到,实际写的不是很多,而且也很模板化,没有太深入学习这个测试框架,今天感觉这个框架的API真的很丰富,功能很强大,因为暂时没有时间去深入挖掘,于是打算在这里先记录一些小的点,以备将来查用:)

1、Mocking protected Method in Superclass


package org.jdesktop.animation.timing.triggers;

import javax.swing.*;

import org.junit.*;

import mockit.*;

import static org.junit.Assert.*;

public final class ActionTriggerTest
{
@Test
public void testAddTrigger()
{
AbstractButton button = new JButton("Test");

ActionTrigger trigger = ActionTrigger.addTrigger(button, null);

assertSame(trigger, button.getActionListeners()[0]);
}

@Test(expected = IllegalArgumentException.class)
public void testAddTriggerFailsOnObjectWithoutAddActionListenerMethod()
{
ActionTrigger.addTrigger(new Object(), null);
}

@Test
public void testActionPerformed()
{
ActionTrigger actionTrigger = new ActionTrigger(null);

new Expectations()
{
Trigger trigger;

{
trigger.fire();
}
};

actionTrigger.actionPerformed(null);
}
}


基本上来说就是在Expectations块中声明一个父类变量,用该变量去调用要测试的方法即可。经实际测试可用。引自[url]code.google.com[/url]


2、 Mocking superclass protected variable using jmockit


@Test
public void testMockStaticVar() {
TestClass testclass = new TestClass();
Deencapsulation.setField(TestClass .class, "staticVar", 2);
//...
}


如此可把TestClass中的static变量staticVar设置成2,但是如果该变量有final修饰则不能进行这样的操作。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值