单元测试java可选与mockito

时间:2018-06-02 00:40:05

标签: java junit mockito

我想测试一个返回Optional客户端的方法。

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

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();
}

我有一个helper类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>

1 个答案:

答案 0 :(得分:0)

这里的问题是,您正在使用不是模拟的东西来调用when。你传递的是Optional

如果我理解你在这里尝试做什么,那么使用doSomething方法将clientHelper传递给对象,并且你想要模拟它以进行测试。如果是这种情况,它通常看起来像这样:

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"));
}