【问题标题】:Unit test java Optional with mockito单元测试 java 可选与 mockito
【发布时间】:2022-02-09 16:03:25
【问题描述】:

我想测试一个在其中返回可选客户端的方法。

我想在客户端为空时测试场景。这不是工作代码,但总体看起来像这样

public Optional<String> doSomething(String place) {
    Optional<Client> client = Optional.empty();
    try {
        client = Optional.ofNullable(clientHelper.get(place));
    } catch (Ex ex) {
        log.warn("Exception occured:", ex);
    }
    return client.isPresent() ? Optional.ofNullable(client.get().getPlaceDetails(place)) : Optional.empty();
}

我有一个帮助类 clientHelper,如果存在则返回基于位置的客户端,如果不存在则抛出异常。 为了测试,这是我想出的

  @Test
public void testClientHelper(){
    ClientHelper clientHelper =  Mockito.mock(ClientHelper.class);
    Optional<Client> client = Optional.empty();
    Mockito.when(Optional.ofNullable(clientHelper.get("IN"))).thenReturn(client);
    assertEquals( doSomething("IN"), Optional.empty())
}

但它返回异常 -

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Optional cannot be returned by get()
get() should return Client

我一直关注这个链接Mockito error with method that returns Optional<T>

【问题讨论】:

    标签: java junit mockito


    【解决方案1】:

    你的问题是你打电话给when 的东西不是模拟的。你传递给它一个Optional

    如果我理解您在此处尝试执行的操作,clientHelper 将通过 doSomething 方法传递给对象,并且您想模拟它以进行测试。如果是这种情况,它通常看起来像这样:

    interface ClientHelper {
        Client get(String place) throws Ex;
    }
    
    class ClassUnderTest {
        private final ClientHelper clientHelper;
    
        public ClassUnderTest(ClientHelper helper) {
            this.clientHelper = helper;
        }
    
        public Optional<String> doSomething(String place) {
            try {
                return Optional.ofNullable(clientHelper.get(place).getPlaceDetails(place));
            } catch (Ex ex) {
                log.warn("Exception: " + ex);
                return Optional.empty();
            }
        }
    }
    
    @Test
    void testFullHelper() {
        Client client = mock(Client.class);
        when(client.getPlaceDetails("IN")).thenReturn("Details");
        ClientHelper helper = mock(ClientHelper.class);
        when(helper.get("IN")).thenReturn(client);
        ClassUnderTest obj = new ClassUnderTest(helper);
        assertEquals("Details", obj.doSomething("IN"));
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多