私は非常に複雑なクラスをJunitテストケースを記述する必要があります。テストを実行するクラスにコンストラクタの初期化があるので、PowerMockitoを使用することにしました。PowerMockito InjectMocksエラーを使用して
私のメインクラスは、このようなものです:
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)
}
}
それ以来、テストケースを実行しているとき、私はnullポインタ例外を取得しています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ののコンストラクタを表示します。そこにエラーが発生する – Jens
なぜあなたはメインクラスをスタブしていますか?あなたがテストしているクラスではありませんか? –
@Jens基本クラスのコンストラクタは、mainClassから渡されたsomeClassを引数として受け取ります。また、このsomeClassを使用して、someClassを使用するコンストラクタも持つ他のいくつかのクラスを初期化するためにこのsomeClassを使用します。 – v1shnu