为Factory类创建的对象注入Mocks [英] Inject Mocks for objects created by Factory classes
问题描述
我有以下课程:
public class MyClass {
private Apple apple;
public void myMethod() {
apple = AppleFactory.createInstance(someStringVariable);
....
....
....
}
}
和Test类:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@InjectMocks
MyClass myClass;
@Test
public void myMethod(){
...
...
...
}
}
我如何在MyClass中将Apple实例作为模拟注入?
How could I inject an Apple instance as a mock in MyClass?
推荐答案
您有3种可能性来解决这个问题:
You have 3 possibilities to solve this:
抽象工厂 :使用具体的工厂类,而不是使用静态方法:
Abstract factory: Instead of using a static method, use a concrete factory class:
public abstract class AppleFactory {
public Apple createInstance(final String str);
}
public class AppleFactoryImpl implements AppleFactory {
public Apple createInstance(final String str) { // Implementation }
}
在您的测试类中,模拟工厂:
In your test class, mock the factory:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private AppleFactory appleFactoryMock;
@Mock
private Apple appleMock;
@InjectMocks
MyClass myClass;
@Before
public void setup() {
when(appleFactoryMock.createInstance(Matchers.anyString()).thenReturn(appleMock);
}
@Test
public void myMethod(){
...
...
...
}
}
PowerMock :使用PowerMock创建静态方法的模拟。查看< a href =https://stackoverflow.com/a/18882873/1920149>我对相关问题的回答,看看它是如何完成的。
PowerMock: Use PowerMock to create a mock of a static method. Look at my answer to a relevant question to see how it's done.
可测试类:将 Apple
创建包装在 protected
方法中并创建测试类覆盖它:
Testable class: Make the Apple
creation wrapped in a protected
method and create a test class that overrides it:
public class MyClass {
private Apple apple;
public void myMethod() {
apple = createApple();
....
....
....
}
protected Apple createApple() {
return AppleFactory.createInstance(someStringVariable);
}
}
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private Apple appleMock;
@InjectMocks
MyClass myClass;
@Test
public void myMethod(){
...
...
...
}
private class TestableMyClass extends MyClass {
@Override
public void createApple() {
return appleMock;
}
}
}
当然,在你的测试中你应该测试的课程 TestableMyClass
而不是 MyClass
。
Of course, in your test class you should test TestableMyClass
and not MyClass
.
我会告诉你我对每种方法的看法:
I'll tell you my opinion on each of the methods:
-
抽象工厂方法是最好的 - 这是一个隐藏实现细节的清晰设计
The abstract factory method is the best one - This is a clear design that hides the implementation details
可测试类 - 是需要最少更改的第二个选项
The testable class - Is the second option which requires minimum changes
这篇关于为Factory类创建的对象注入Mocks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!