【问题标题】:JUnit test always returning nullJUnit 测试总是返回 null
【发布时间】:2019-05-27 10:35:40
【问题描述】:

我正在为我的代码编写一个 JUnit 测试用例,但 Mockito 总是返回 null

@Component
public class ConnectorImpl {

    public String returnString(String inte) {

        String x = testing();
        return x;
    }

    public String testing() {
        return "test";
    }
}

测试类

@RunWith(MockitoJUnitRunner.class)
public class ConnectorImplTest  {

    @Mock public ConnectorImpl connector;

    @Test
    public void testLoggedInRefill() throws Exception {

        Mockito.when(connector.testing()).thenReturn("test");


        String x = connector.returnString("8807");

        assertEquals("8807", x);
    }

}

当我调用connector.returnString("8807"); 时,它总是返回null。有什么我做错了吗?我是 JUnit 的新手。

【问题讨论】:

  • Mockito - spy vs mock的可能重复
  • tl;dr:你想要Spy,而不是Mock。顺便说一句:不要模拟testing(),你应该模拟对returnString("8807");的调用(然后你可以继续使用Mocks)

标签: java junit mockito


【解决方案1】:

您可以测试您的方法returnString 的一种方法是:

// mock 'returnString' method call
Mockito.when(connector.returnString(anyString()).thenReturn("test"); 
// assert that you've mocked succesfully
assertEquals("test", connector.returnString("8807"));

【讨论】:

    【解决方案2】:

    根据你的代码,你在嘲笑你的ConnectorImpl

    所以它是一个空对象,这意味着您可以专门when(...).then(...) 任何您想测试的功能。

    顺便说一句 - 如果你正在测试 ConnectorImpl 那么你不应该模拟它,而应该使用真正的 bean。您应该模拟 ConnectorImpl 正在使用的 bean。

    所以我建议你的代码看起来可能是这样的:

    @RunWith(MockitoJUnitRunner.class)
    public class ConnectorImplTest  {
    
        public ConnectorImpl connector = new ConnectorImpl(...);
    
        @Test
        public void testLoggedInRefill() throws Exception {
            String x = connector.returnString("8807");
            assertEquals("8807", x);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您正在模拟对象,并且没有为被模拟对象的 returnString 方法指定任何行为。正如你对 testing() 所做的那样,你可以对 returnString() 方法做同样的事情:

      when(connector.returnString(anyString())).thenReturn("text")

      另一方面,你为什么需要模拟这个类?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多