是否可以在构造函数中使用模拟?在构造函数中使用模拟
Class A{
public B b = new B();
public A(String input){
//I need to stub this method
b.someMethod(input);
}
// Class implementations
}
单元测试:
Class ATest{
@Mock
B b;
@InjectMock
A a;
//option1:
@Before
setup(){
MockitoAnnotations.initMocks(this); //Fails - since A isnt instantiated
a = new A();
}
//option2:
@Before
setup(){
a = new A();
MockitoAnnotations.initMocks(this); // Fails in new A() due to method i want to stub as mocks werent initialized yet !
}
}
我该如何处理这个?提前致谢。
你真的应该避免在构造函数中做逻辑。 – vertti 2013-05-01 04:53:54
如果您省略'a = new A();',选项1会失败吗?我希望'@ InjectMocks'注释可以在调用'initMocks'的时候为你实例化'A'。对于备用选项,您可能会从https://code.google.com/p/mockito/wiki/MockingObjectCreation获得一些乐趣 – 2013-05-01 05:48:25
是的,它没有抱怨它必须实例化 – broun 2013-05-02 04:59:02