简体   繁体   中英

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. 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:

@Mock
private DBproperties dbprop;

Then remove the dbprop mock creation from your test method:

@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:

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

Or call the following in a @Before method:

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

See the MockitoAnnotations and MockitoJUnitRunner JavaDocs for more information on the two approaches.

You can annotate your Object with @Mock, so its look like this

@Mock DBproperties dbProperties;@Before public void init(){ MockitoAnnotations.initMocks(this); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM