简体   繁体   中英

Mockito - Spring unit tests

I've been learning more about the Mockito framework within Java and I'm lost about what to do to complete this unit test.

Basically, the error from the console states that there is a NullPointerException when the Bar.sayHi() method is trying to be run from the Foo test. I suspect it has something to do with the autowired fields (but I maybe wrong)?

Below is a simple example of the problem that I'm running into:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {

    @Mock
    //@Spy // Cannot spy on an interface
    IBar bar;

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

    @Test
    public void test() {

        // Given 
        FooImpl foo = new FooImpl();
        foo.saySaySay();

        // When

        // Then

    }

}

Here's the FooImpl class under testing (there's an interface for Foo):

public class FooImpl implements IFoo {

    @Autowired
    private IBar bar;

    public void saySaySay() {
        bar.sayHi();
    }

}

And the Bar class (there's also an interface for Bar):

public class BarImpl implements IBar {

    @Override
    public void sayHi() {
        System.out.println("hello");
    }

}

Does anyone has a suggestion on this? Thanks.

Just creating a mock of Ibar will not inject that mock into the @Autowired field. Autowiring is the job of Spring, not Mockito. You need to explicitly tell mockito to inject those into testing objects using @InjectMock

@RunWith(MockitoJUnitRunner.class)
public class FooTest {
    @InjectMocks
    FooImpl foo;

    @Mock
    IBar bar;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
    @Test
    public void test() {
        foo.saySaySay();
    }

}

or manual set the mock object inside the tested object.

@Test
public void test() {
    FooImpl foo = new FooImpl();
    ReflectionTestUtils.setField(foo, "bar", bar);
    foo.saySaySay();    
}
RunWith(MockitoJUnitRunner.class)
public class FooTest {

    @Mock
    //@Spy // Cannot spy on an interface
    IBar bar;


    @InjectMocks
    private FooImpl foo;
    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {

        // Given 
        foo.saySaySay();
        verify(bar).sayHi();
        // When

        // Then

    }

}

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