2016-06-16 2 views
-1

У меня есть этот тест:Получение NullPointerException в моем макете зависимости

@RunWith(MockitoJUnitRunner.class) 
public class MainClassTest { 

@Mock 
Dependence dependence; 

@InjectMocks 
MainClass mainClassTester; 

} 

И этот тест:

@Test 
    public void testA() { 
    when(dependence.getStatus()).thenReturn(true); 
    mainClassTester.startStatusOperation(); 

    } 

Мой класс MainClass выглядит следующим образом:

public class MainClass{ 

private Dependence dependence = new Dependence() ; 

public boolean startStatusOperation(){ 
    boolean status = dependence.getStatus(); 
    [...] 
} 
} 

Im получая NullPointer в этом line:

boolean status = dependence.getStatus(); 

Почему не притворная «зависимость» не работает? Этот код всегда работал, когда я использовал @inject, но не могу использовать его.

+0

У вас есть конструктор для вашего MainClass? – Vijay

+1

Если вам нужна помощь, вам придется опубликовать трассировку стека COMPLETE. –

ответ

-1

Если вы хотите использовать конструктор для создания объекта вместо @Inject, вам нужно высмеять конструктор, а не просто использовать @Mock.

@InjectMock будет вводить только поле, которое вы используете @Inject. Если у вас есть какое-либо поле, которое устанавливается новым конструктором, это не будет вводиться в тестовый объект, если вы используете @InjectMock. От http://site.mockito.org/mockito/docs/current/org/mockito/InjectMocks.html

@Documented 
@Target(value=FIELD) 
@Retention(value=RUNTIME) 
public @interface InjectMocks 
Mark a field on which injection should be performed. 
Allows shorthand mock and spy injection. 
Minimizes repetitive mock and spy injection. 
Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection in order and as described below. If any of the following strategy fail, then Mockito won't report failure; i.e. you will have to provide dependencies yourself. 

Constructor injection; the biggest constructor is chosen, then arguments are resolved with mocks declared in the test only. If the object is successfully created with the constructor, then Mockito won't try the other strategies. Mockito has decided to no corrupt an object if it has a parametered constructor. 
Note: If arguments can not be found, then null is passed. If non-mockable types are wanted, then constructor injection won't happen. In these cases, you will have to satisfy dependencies yourself. 

Property setter injection; mocks will first be resolved by type (if a single type match injection will happen regardless of the name), then, if there is several property of the same type, by the match of the property name and the mock name. 
Note 1: If you have properties with the same type (or same erasure), it's better to name all @Mock annotated fields with the matching properties, otherwise Mockito might get confused and injection won't happen. 

Note 2: If @InjectMocks instance wasn't initialized before and have a no-arg constructor, then it will be initialized with this constructor. 

Field injection; mocks will first be resolved by type (if a single type match injection will happen regardless of the name), then, if there is several property of the same type, by the match of the field name and the mock name. 
Note 1: If you have fields with the same type (or same erasure), it's better to name all @Mock annotated fields with the matching fields, otherwise Mockito might get confused and injection won't happen. 

Note 2: If @InjectMocks instance wasn't initialized before and have a no-arg constructor, then it will be initialized with this constructor. 
+0

Thats it, я не могу использовать injectMocks без @injects, мне нужен конструктор, который устанавливает мой атрибут или метод setter. Спасибо за помощь. – deveduardo

Смежные вопросы