简体   繁体   English

Mockito-弹簧单元测试

[英]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. 我一直在学习有关Java中Mockito框架的更多信息,而我不知道如何完成此单元测试。

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. 基本上,来自控制台的错误指出,当尝试从Foo测试运行Bar.sayHi()方法时,会出现NullPointerException。 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): 这是正在测试的FooImpl类(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): 还有Bar类(还有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. 仅创建Ibar的模拟项不会将该模拟项注入@Autowired字段。 Autowiring is the job of Spring, not Mockito. 自动装配是Spring的工作,而不是Mockito。 You need to explicitly tell mockito to inject those into testing objects using @InjectMock 您需要显式告诉mockito使用@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

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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