Ich schreibe Einheit für den folgenden Code, ich bekomme NPE, obwohl ich die Felder verspottete, wie kann ich das auflösen. Diese Felder sind vorhanden mit @Inject AnmerkungWie kommt man mit NPE für @Inject-Feld während der Unit-Tests?
@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();
}
}
So wie kann ich den verspotteten Wert in der aktuellen Klasse, wo das Feld mit @Inject mit Mockito injiziert wird?
Hey vielen Dank für die Antwort, dieser Code ist nur zum Beispiel und nicht meine eigentliche Code. Es wurde vorgeschlagen, entweder @RunWith (MockitoJUnitRunner.class) oder MockitoAnnotations.initMocks (this) - zu verwenden, siehe http://stackoverflow.com/a/28969255/2340345 – user2340345