JMockit期望API返回输入参数



我知道,如果我想模仿一个方法并根据其输入为其分配特定行为,我可以使用MockUps API:

public class DuplicationTest {
    static class Duplicator {
        public String duplicate(String str) { return null; }
    }
    @Test
    public void verifySameStringReturnedWithMockupsAPI() throws Exception {
        new MockUp<Duplicator>() {
            @Mock public String duplicate(String str) { return str; }
        };
        Duplicator dup = new Duplicator();
        assertEquals("test", dup.duplicate("test"));
    }
}

此测试通过
然而,有时我没有使用MockUps API的奢侈(例如,当嘲笑静态类时),因此我只能使用Expecteds API:

@Test
public void verifySameStringReturnedWithExpectationsAPI(@Mocked Duplicator dup) throws Exception {
    new Expectations() {{
        dup.duplicate(anyString); result = anyString;
    }};
    assertEquals("test", dup.duplicate("test"));
}

这显然是失败的。对dup.duplicate("test")的调用返回一个空的String(可能是某种默认值)。有办法绕过它吗?

受Rogério评论的启发,我设法使用Delegate:解决了这个问题

@SuppressWarnings("unused")
@Test
public void verifySameStringReturnedWithExpectationsAPI(@Mocked Duplicator dup) throws Exception {
    new Expectations() {{
        dup.duplicate(anyString);
        result = new Delegate<String>() { String delegate(String str) { return str; }};
    }};
    assertEquals("test", dup.duplicate("test"));
    assertEquals("delegate did it", dup.duplicate("delegate did it"));
}

这不是最优雅的解决方案,如果Delegate类是@FunctionalInterface(我知道这将在JMockit的下一个主要版本中发生),它看起来会更好。目前,这似乎是根据Expecteds API中的输入参数模拟行为的唯一方法。

在第二个示例中,它返回一个空字符串,因为您正在设置result = anyString。anyString是一个jmockit对象,用于匹配任何可能的字符串值。相反,您要做的是将结果设置为实际要返回的值,在本例中为result = "test"

最新更新