2
我爲下面的代碼編寫單元測試,即使我嘲笑字段,即時獲取NPE,我該如何解決這個問題。這些領域都存在與@Inject註解如何在單元測試時使用NPE for @Inject字段?
@Component
interface A {
void run();
}
class B {
@Inject
A a;
void someMethod() {
a.run();
}}
class C{
@Inject
B b;
void anotherMethod() {
b.someMethod();
}
}
class CTest {
@Mock
B b;
// remains null when invoked in the actual class though its mocked instance is
// present here
@Mock
A a;
//// remains null when invoked in the actual class though its mocked instance
//// is present here
@InjectMocks
C c;
@Before
public void initialize() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
c.anotherMethod();
}
}
所以,我怎麼能得到其中場被注射使用的Mockito @Inject在實際的類嘲笑價值?
嘿謝謝你的答案,這段代碼只是例子而不是我的實際代碼。它建議使用@RunWith(MockitoJUnitRunner.class)或MockitoAnnotations.initMocks(this) - 參考http://stackoverflow.com/a/28969255/2340345 – user2340345