我正在進行單元測試的類需要一個依賴項並調用該依賴項的函數。該函數將一個複雜的對象作爲參數,併產生一個結果。現在,我想嘲笑依賴關係,並根據傳入的參數返回一些內容。下面給出了一個簡化的工作版本。在模擬類中使用Java8 lambda進行參數匹配
我可以在when
方法中使用Java 8 lambda表達式來消除ArgHasNext
類嗎?像下面的註釋代碼(不編譯)。
class ArgHasNext implements ArgumentMatcher<Arg> {
public boolean matches(Arg arg) {
return arg.hasNext();
}
@Override
public boolean matches(Object o) {
return matches((Arg)o);
}
}
@RunWith(MockitoJUnitRunner.class)
public class ArgumentMatcherTest {
@Mock
private Dependency dep = mock(Dependency.class);
@Test
public void test() {
when(dep.func(argThat(new ArgHasNext()))).thenReturn(true);
// when(dep.func(argThat((Arg a) -> a.hasNext()))).thenReturn(true);
// when(dep.func(argThat((Arg a) -> !a.hasNext()))).thenReturn(false);
Sut sut = new Sut(dep);
assertEquals(sut.method(new Arg(true)), "True");
assertEquals(sut.method(new Arg(false)), "False");
}
}
class Arg {
private boolean hasNext;
public Arg(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean hasNext() {
return this.hasNext;
}
}
class Sut {
private Dependency dep;
public Sut(Dependency dep) {
this.dep = dep;
}
public String method(Arg arg) {
if (dep.func(arg)) {
return "True";
}
else {
return "False";
}
}
}
class Dependency {
public boolean func(Arg arg) {
if (arg.hasNext()) {
return true;
}
return false;
}
}
我正在使用Mockito核心版本2.0.54-beta。
編輯 好吧,也許我過分簡化了這個例子。在實際情況中,依賴項func
方法返回在被測試方法返回之前在SUT
中處理的分頁查詢結果。根據Arg
,我希望依賴項func
在第一次調用結果時返回第1頁結果,第2次結果返回結果。我只能做到這一點,當我可以根據傳遞給函數調用的參數模擬返回不同的值。這可能在Mockito中使用lambdas?現在
只是想知道:爲什麼你使用的是一個幾年前的2.0測試版?也許:你能舉一個例子,你如何設想在這裏使用lambdas? – GhostCat
@GhostCat查看測試方法中的兩條註釋行。我認爲這兩條線更具表現力(如果它們能奏效)。 ArgumentMatcher派生類可以工作,但並不明顯。 – MvdD
也許我錯過了一些東西,但我認爲你是在錯誤的地方投入你的時間。看到我的答案。 – GhostCat