I have a class which returns different Strings. I want to be able to stub all the methods in this class without having to explicitly stub each methods. Does mockito have stub by regex?
Thanks
You can implement the Answer
interface to do what you want. Here's a test case showing it in action:
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;
}
}
}
Instead of using contains
you can use a regex matcher if you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.