我有一个非常复杂的类来编写Junit测试用例。我决定使用PowerMockito,因为要运行测试的类具有构造函数初始化。
我的主课是这样的:
public class MainClass extends BaseClass{
MainClass(SomeClass class){
super(class);
}
public void methodToBeTested(){
some code here
}
..few other methods which I am not going to test.
}
现在我已经编写了这样的测试用例:
@RunWith(PowerMockRunner.class)
public class TestClass{
@Mock
OtherClassUsedInMainClass mock1;
@Mock
OtherClassUsedInMainClass mock2;
@InjectMocks
MainClass mainClass;
@Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
PowerMockito.whenNew(MainClass.class).withArguments(Mockito.any(SomeClass.class))
.thenReturn(mainClass);)
}
@Test
public void testMethodtobeTested(){
...I am using the other objects to mock data and test if this method works fine
mainClass.methodtobeTested();
\\This method will increment a value. I am just asserting if that value is right.
Assert.assertEquals(mainClass.checkCount(),RequiredCount)
}
}
在运行测试用例时,我将得到一个空指针异常,因为它试图初始化mainClass。它不会被嘲笑。我知道我做错了什么。但我只是不知道那是什么。
错误:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'mainClass' of type 'class com.main.MainClass'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
Caused by: java.lang.NullPointerException
This null pointer exception is thrown from a the constructor of the BaseClass when it tries to initialize another class.
发布于 2016-07-20 08:44:33
This question解释了@Mock
和@InjectMocks
的区别
@Mock
创建一个模拟。@InjectMocks
创建类的一个实例,并将用@Mock
(或@Spy
)注释创建的模拟注入到这个实例中。
MainClass
构造函数需要一个SomeClass
参数,但没有任何模拟。
您的代码应该类似于:
@RunWith(PowerMockRunner.class)
public class TestClass{
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
SomeClass mock1;
@InjectMocks
MainClass mainClass;
@Before
public void setUp() throws Exception{
...
发布于 2016-07-20 08:38:42
引用this answer,它引用了 documentation
构造函数注入;选择最大的构造函数,然后使用仅在测试中声明的模拟解析参数。注意:如果找不到参数,则传递null。
因此,想必,声明一个类型为SomeClass
的字段,并对其@Mock
进行注释。
发布于 2016-07-21 10:01:39
如果您不能向我们展示实际的代码,那么很难猜出到底发生了什么。但是,您的模拟SomeClass
似乎需要一些短截的行为来满足BaseClass构造函数。
例如:
// the instance of MainClass you run your tests against
private MainClass instance;
@Mock
private SomeClass someClass;
@Mock
private SomethingElse somethingElse;
@Before
public void setUp() {
when(someClass.doSomething()).thenReturn(somethingElse);
instance = new MainClass(someClass);
}
@Test
public void test() {
// SETUP
when(somethingElse.doWeirdStuff()).thenThrow(new WeirdException());
// CALL
instance.performTapDance();
// VERIFY
assertTrue(instance.isWeird());
}
https://stackoverflow.com/questions/38476209
复制相似问题