jmock测试的准备工作

private Mockery context = new JUnit4Mockery() {
        {
            setImposteriser(ClassImposteriser.INSTANCE);
        }
    };

注意这里的setImposteriser(ClassImposteriser.INSTANCE);
因为默认的JUnit4Mockery的Imposteriser是JavaReflectionImposteriser,他是针对接口进行mock的,如果要针对class进行mock,必须setImposteriser(ClassImposteriser.INSTANCE);
这样之后context便可以对class进行mock了


官方的文档:

Mocking Classes with jMock and the ClassImposteriser

Because it uses Java's standard reflection capability, the default configuration of the jMock framework can only mock interfaces, not classes. (Actually, we consider that to be a good thing because it encourages the design to focus on communication between objects rather than static classification or data storage). However, the ClassImposteriser extension class uses the CGLIB 2.11 and Objenesis2 libraries to create mock objects of classes as well as interfaces. This is useful when working with legacy code to tease apart dependencies between tightly coupled classes.

To use the ClassImposteriser:

  1. Add jmock-legacy-2.1.0-RCn.jar, cglib-nodep-2.1_3.jar and objenesis-1.0.jar to your CLASSPATH.
  2. Plug the ClassImposteriser into the Mockery of your test class:

    Raw

    import org.jmock.Mockery;
    import org.jmock.Expectations;
    import org.jmock.lib.legacy.ClassImposteriser;

    public class ConcreteClassTest extends TestCase {
    private Mockery context = new Mockery() {{
    setImposteriser(ClassImposteriser.INSTANCE);
    }};

    ...
    }

    JUnit 3

    import org.jmock.Expectations;
    import org.jmock.integration.junit3.MockObjectTestCase;
    import org.jmock.lib.legacy.ClassImposteriser;

    public class ConcreteClassTest extends MockObjectTestCase {
    {
    setImposteriser(ClassImposteriser.INSTANCE);
    }

    ...
    }

    JUnit 4

    import org.jmock.Mockery;
    import org.jmock.Expectations;
    import org.jmock.integration.junit4.JUnit4Mockery;
    import org.jmock.lib.legacy.ClassImposteriser;

    @RunWith(JMock.class)
    public class ConcreteClassTest {
    private Mockery context = new JUnit4Mockery() {{
    setImposteriser(ClassImposteriser.INSTANCE);
    }};

    ...
    }
  3. Your tests can now create mocks of abstract or even concrete classes:
    Graphics g = context.mock(java.awt.Graphics.class);

posted on 2007-12-05 10:54 刘铮 阅读(898) 评论(0)  编辑  收藏 所属分类: Jmock


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年12月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论