代码之家  ›  专栏  ›  技术社区  ›  MeanwhileInHell

调用返回Future<Void>在单元测试中抛出NPE

  •  2
  • MeanwhileInHell  · 技术社区  · 7 年前

    @Override
    public void stop() {
    
        if (client != null) {
            Future<Void> disconnectClient = client.disconnect();
    
            try {
                disconnectClient.await();
            } catch (InterruptedException e) {
                logger.info("Failed to disconnect client: ", e.getLocalizedMessage());
            }
        } else {
            logger.error("Client does not exist.");
        }
    }
    

    其中 disconnect() 返回a Future<Void> . 一个简单的测试如下所示:

    @Mock
    private MyClient client;
    
    @InjectMocks
    private MyServer objectUnderTest = new MyServer();
    
    @Test
    public void shouldCallDisconnectOnClientWhenDefined() throws Exception {
        objectUnderTest.stop();
        verify(client, times(1)).disconnect();
    }
    

    当我运行这个时,我显然在 Future when() 将来

    MyServer 包含一个 client 连接器,在初始化时连接到外部服务器 MyServer . 倍数 可以创建,每个都有自己到外部服务器的通道,通过 . 的所有实例 MyServerRegistry . 当不再需要连接时 将断开,并且 实例已从注册表中删除。

    客户 不是自动连接到MyServer,而是初始化并在的构造函数中打开连接 MyServer 呼叫返回 未来<Void> .

    2 回复  |  直到 7 年前
        1
  •  2
  •   GhostCat    7 年前

    那么简单的呢:

    when(client.disconnect()).thenReturn(mockedFuture);
    

    client 对象是 你的 disconnect() 方法该方法在模拟中调用;它返回一个值,因此您可以模拟它!

    (除非 MyClient 断开()

        2
  •  0
  •   DwB    7 年前

    这个 NullPointerException 是因为模拟对象的默认行为是返回null。 因此 disconnect() client 嘲弄

    假设 @Autowired MyServer 断开() 方法既不是静态的,也不是最终的(似乎是这样), 客户 对象,然后定义 断开() 方法

    将此变量添加到测试中:

    @Mock
    Future<Void> mockFuture;
    

    将此行为添加到模拟中

    doReturn(mockFuture).when(client).disconnect();