[英]autowired dependency not getting mocked while executing test case with junit and mockito
I am using Junit4 and Mockito for test cases, in the following code dbprop.getProperty("config")
is throwing a NullPointerException
because dbProp is null. 我在测试用例中使用Junit4和Mockito,在下面的代码中, dbprop.getProperty("config")
抛出NullPointerException
因为dbProp为null。 Please help me out why it was not mocked? 请帮帮我,为什么它没有被嘲笑?
public abstract class BaseClass {
@Autowired
protected DBproperties dbprop;
}
public class SampleClass extends BaseClass {
@Autowired
private OrderService orderService;
valdiateOrder(String input) {
String config = dbprop.getProperty("config");
}
}
public class TestSampleClass {
@InjectMocks
SampleClass sampleClass;
@Mock
private OrderService orderService;
@Test
public void testValidateOrder() {
DBproperties dbprop = mock(DBproperties .class);
when(dbprop.getProperty("config")).thenReturn("xxxx");
assertNotNull(SampleClass.valdiateOrder("xxx"));
}
}
Your dbprop
mock has not been injected into sampleClass
, you need to add: 您的dbprop
mock尚未注入sampleClass
,您需要添加:
@Mock
private DBproperties dbprop;
Then remove the dbprop
mock creation from your test method: 然后从测试方法中删除dbprop
模拟创建:
@Test
public void testValidateOrder() {
// DBproperties dbprop = mock(DBproperties .class); <-- removed
when(dbprop.getProperty("config")).thenReturn("xxxx");
assertNotNull(SampleClass.valdiateOrder("xxx"));
}
Next, to ensure mocks are injected when using the @InjectMocks
annotations you need to either add the following runner: 接下来,为了确保在使用@InjectMocks
注释时注入@InjectMocks
您需要添加以下运行器:
@RunWith(MockitoJUnitRunner.class)
public class TestSampleClass {
...
Or call the following in a @Before
method: 或者在@Before
方法中调用以下内容:
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
See the MockitoAnnotations and MockitoJUnitRunner JavaDocs for more information on the two approaches. 有关这两种方法的更多信息,请参阅MockitoAnnotations和MockitoJUnitRunner JavaDocs。
You can annotate your Object with @Mock, so its look like this 你可以用@Mock注释你的对象,所以它看起来像这样
@Mock DBproperties dbProperties;@Before public void init(){ MockitoAnnotations.initMocks(this); @Mock DBproperties dbProperties; @Before public void init(){MockitoAnnotations.initMocks(this); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.