![](/img/trans.png)
[英]How to stub parent class method call in my mocked abstract class that I want to test using PowerMock
[英]How to stub all the method in the same mocked class
我有一個返回不同字符串的類。 我希望能夠對此類中的所有方法進行存根,而不必顯式對每個方法進行存根。 Mockito是否通過正則表達式存根?
謝謝
您可以實現Answer
接口來執行您想要的操作。 這是一個測試案例,展示了它的實際作用:
package com.sandbox;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class SandboxTest {
@Test
public void testMocking() {
Foo foo = mock(Foo.class, new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String name = invocation.getMethod().getName();
if (name.contains("get")) {
return "this is a getter";
}
return null;
}
});
assertEquals("this is a getter", foo.getY());
assertEquals("this is a getter", foo.getX());
}
public static class Foo {
private String x;
private String y;
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
}
}
如果需要,可以使用正則表達式匹配器來代替使用contains
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.