我有一个如下的类:
public class A {
public A(String test) {
bla bla bla
}
public String check() {
bla bla bla
}
}
构造函数A(String test)
和check()
中的逻辑是我试图模拟的东西。我想要任何像这样的调用:new A($$$any string$$$).check()
返回一个伪字符串"test"
。
我试过了:
A a = mock(A.class);
when(a.check()).thenReturn("test");
String test = a.check(); // to this point, everything works. test shows as "tests"
whenNew(A.class).withArguments(Matchers.anyString()).thenReturn(rk);
// also tried:
//whenNew(A.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(rk);
new A("random string").check(); // this doesn't work
但它似乎不起作用。new A($$$any string$$$).check()
仍在遍历构造函数逻辑,而不是获取A
的模拟对象。
发布于 2012-11-14 01:32:43
您发布的代码适用于最新版本的Mockito和Powermockito。也许你还没有准备好A?试试这个:
A.java
public class A {
private final String test;
public A(String test) {
this.test = test;
}
public String check() {
return "checked " + this.test;
}
}
MockA.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {
@Test
public void test_not_mocked() throws Throwable {
assertThat(new A("random string").check(), equalTo("checked random string"));
}
@Test
public void test_mocked() throws Throwable {
A a = mock(A.class);
when(a.check()).thenReturn("test");
PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
assertThat(new A("random string").check(), equalTo("test"));
}
}
两个测试都应该通过mockito 1.9.0、powermockito 1.4.12和junit 4.8.2的测试
发布于 2020-02-27 17:23:48
在Mockito中,你可以使用withSettings()
。例如,如果CounterService
需要2个依赖项,您可以将它们作为模拟进行传递:
UserService userService = Mockito.mock(UserService.class);
SearchService searchService = Mockito.mock(SearchService.class);
CounterService counterService = Mockito.mock(CounterService.class, withSettings().useConstructor(userService, searchService));
https://stackoverflow.com/questions/13364406
复制相似问题