【问题标题】:JUnit mock of Environment with Mockito not working, evaluating to null still带有 Mockito 的环境的 JUnit 模拟不起作用,仍然评估为 null
【发布时间】:2018-06-23 15:48:43
【问题描述】:

我有一个班级MyClass,里面有@Autowired private Environment env;。它还有public MyFunctionA(),它调用private MyFunctionB(),在MyFunctionB() 中,它调用env.getProperty(propName),它将一个字符串值从属性文件返回到MyFunctionA(),作为计算的一个因素。但是目前,在调试 JUnit 测试时,我无法在没有得到 null 的情况下模拟 env。

MyClass 的单元测试类MyServiceTest 开头如下:

public class MyServiceTest {

    @Mock 
    final Environment env = Mockito.mock(Environment.class);

    MyServiceImpl myService;

    @Before
    public void setUp() throws Exception {
       Mockito.when(this.env.getProperty("myProperty")).thenReturn("1234,2345");

        myService = new MyServiceImpl();

稍后,在单元测试函数中,它调用了MyFunctionA(),但调试显示MyFunctionB() 在进行env.getProperty 调用时遇到了NPE。有什么问题?测试如下:

@Test
public void myUnitTest() throws IOException {
    boolean boolFlag = myService.MyFunctionA();
    assertTrue(boolFLag);
}

【问题讨论】:

    标签: java junit mockito autowired


    【解决方案1】:

    这里有两个问题:

    1. 您可以通过为env 显式分配一个新的(模拟的)值来覆盖由@Mock 注释创建的模拟对象。
    2. 您缺少 @InjectMocks 注释,无法将模拟的 env 注入您的 myService 成员:


    public class MyServiceTest {
    
        @Mock 
        Environment env; // issue #1
    
        @InjectMocks // issue #2
        MyServiceImpl myService = new MyServiceImpl()
    
        @Before
        public void setUp() throws Exception {
           Mockito.when(this.env.getProperty("myProperty")).thenReturn("1234,2345");
        }
    
        // Tests ...
    

    【讨论】:

    • Mockito.doReturn("1234,2345").when(this.env.getProperty("myProperty"));
    【解决方案2】:

    就像@Mureinik 所说,您的对象创建有问题。但是,如果你依赖来自 Mockito 的注解,你需要使用 runner MockitoJUnitRunner 或调用 MockitoAnnotations.initMocks(this); 来初始化对象

    最终配置:

    public class MyServiceTest {
    
    @Mock 
    Environment env;
    
    @InjectMocks
    MyServiceImpl myService;
    
    @Before
    public void setUp() throws Exception {
       MockitoAnnotations.initMocks(this);
       Mockito.when(this.env.getProperty("myProperty")).thenReturn("1234,2345");
    }
    
    // Tests ...
    

    【讨论】:

    • this.env.getProperty("myProperty") 找不到 get 方法...请帮忙!
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2021-05-08
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多