【发布时间】:2016-07-20 08:32:30
【问题描述】:
我有一个非常复杂的类来编写 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.
【问题讨论】:
-
显示BaseClass的构造函数。出现错误
-
为什么要存根 MainClass?这不是你正在测试的课程吗?
-
@Jens 基类构造函数接受从 mainClass 传递的 someClass 作为参数。它还使用这个 someClass 并用它来初始化一些其他类,这些类也有一个使用 someClass 的构造函数。
-
@AdriaanKoster 你能解释一下吗?
-
你不应该做类似
PowerMockito.whenNew(MainClass.class).withArguments(Mockito.any(SomeClass.class)).thenReturn(mainClass);)的事情。您应该在没有任何存根行为的情况下针对 MainClass 的普通实例进行测试。
标签: java mockito powermockito