简体   繁体   English

我可以使用jmock替换工厂返回的实现吗?

[英]Can I use jmock to replace an implementation returned by a factory?

I have a factory that returns an interface FormatService : 我有一个返回接口FormatService的工厂:

public class FormatServiceFactory {
    public FormatService getService() {
        ...
    }
}

Is it possible to mock out this factory so that it will always return a stub implementation of FormatService - FormatServiceStub in our unit tests? 是否可以模拟该工厂,以便在我们的单元测试中始终返回FormatService - FormatServiceStub的存根实现?

Depends. 要看。 How is the factory obtained/used by the code under test? 被测代码如何获得/使用工厂?

If it's instantiated explicitly in the methods you're testing, or if it's a static factory, you won't be able to mock it. 如果在您要测试的方法中显式实例化了它,或者它是一个静态工厂,则将无法对其进行模拟。

If it's injected into the object under test, you can create and inject the mocked factory before executing the test. 如果将其注入到测试对象中,则可以在执行测试之前创建并注入模拟工厂。

Mocking the factory should be easy enough with JMock. 使用JMock模拟工厂应该很容易。 From your example code, it looks like it's a class, not an interface, so you'll either need to use the cglib version of JMock and the MockObjectTestCase class in the cglib package for JMock 1, or the ClassImposteriser for JMock 2. 从示例代码来看,它看起来像是一个类,而不是接口,因此您需要在JMock 1的cglib软件包中使用JMock的cglib版本和MockObjectTestCase类,在JMock 2的ClassImposteriser中使用。

Once mocked, you can make it return your stubbed implementation (or even a mock FormatService) when you define the expectations for the getService() method. 一旦被模拟,您可以在定义getService()方法的期望时使其返回已存根的实现(甚至是模拟FormatService)。

Mockery mockery = new JUnit4Mockery() {{setImposteriser(ClassImposteriser.INSTANCE);}}; 模拟嘲笑= new JUnit4Mockery(){{setImposteriser(ClassImposteriser.INSTANCE);}};

final FormatServiceFactory factory = mockery.mock(FormatServiceFactory .class); 最终的FormatServiceFactory工厂= mockery.mock(FormatServiceFactory .class);

context.checking(new Expectations() {{ oneOf (factory ).getService(); will(returnValue(new FormatServiceMock())); }}); context.checking(new Expectations(){{oneOf(factory).getService(); will(returnValue(new FormatServiceMock()));}}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM