我在测试用例中使用Junit4和Mockito,在以下代码中,由于dbProp为null,因此dbprop.getProperty("config")抛出NullPointerException。请帮助我,为什么不嘲笑它?

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"));
    }
}

最佳答案

您的dbprop模拟尚未被注入到sampleClass中,您需要添加:

@Mock
private DBproperties dbprop;


然后从测试方法中删除dbprop模拟创建:

@Test
public void testValidateOrder() {
    // DBproperties dbprop = mock(DBproperties .class); <-- removed
    when(dbprop.getProperty("config")).thenReturn("xxxx");
    assertNotNull(SampleClass.valdiateOrder("xxx"));
}


接下来,要确保在使用@InjectMocks注释时注入模拟,您需要添加以下运行器:

@RunWith(MockitoJUnitRunner.class)
public class TestSampleClass {
...


或在@Before方法中调用以下内容:

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}


有关这两种方法的更多信息,请参见MockitoAnnotationsMockitoJUnitRunner JavaDocs。

09-25 21:58