我是Mockito的新手,我想知道如何存根获取/设置对.
例如
public interface Dummy {
public String getString();
public void setString(String string);
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使它们正常运行:如果我在调用的某个地方调用,setString("something");我想getString()返回"某些东西".这是可行的还是有更好的方法来处理这种情况?
有什么区别:
verify(mock, times(1)).myMethod(Matchers.isA(String.class));
verify(mock, times(1)).myMethod(Matchers.anyString());
Run Code Online (Sandbox Code Playgroud)
来自Mockito图书馆?两者都通过我的方法,我想知道哪一个"更好"使用.
我一直面临着一个特殊的问题.基本上,当我正常运行我的Mockito/PowerMockito测试,即'Run as Junit Test'时,它会给我以下错误:
java.lang.NoSuchMethodError: org.mockito.mock.MockCreationSettings.isUsingConstructor()Z
at org.mockito.internal.creation.instance.InstantiatorProvider.getInstantiator(InstantiatorProvider.java:10)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:110)
at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:58)
at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:203)
at org.powermock.api.extension.listener.AnnotationEnabler.standardInject(AnnotationEnabler.java:106)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:54)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:90)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:292)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Run Code Online (Sandbox Code Playgroud)
我曾尝试在maven依赖项和构建路径中添加所有必需的jar,但无济于事.
但是,我随后在运行配置 - >类路径 - >用户条目中手动添加了jar.然后,我像往常一样运行测试,它显示绿色状态栏,即它运行完美.
请帮帮我.我需要在没有这些令人讨厌的变化的情况下进行测试,这会影响我的工作.我能做什么才能让我通常运行测试,即不用一直运行配置,只需在构建路径中添加jar然后"运行为junit test"?
我想在运行 void 方法时抛出异常
when(booking.validate(any())).thenThrow(BookingException.builder().build());
Run Code Online (Sandbox Code Playgroud)
但我有一个编译错误:
Required type: T
Provided: void
reason: no instance(s) of type variable(s) T exist so that void conforms to T
Run Code Online (Sandbox Code Playgroud) 我试图在测试中验证是否调用了静态方法。我正在使用 Mockito 来达到这个目的。
这个问题与此类似。但是,最高票数回复中建议的解决方案不再适用,因为 MockedStatic 验证方法已被弃用。
try (MockedStatic<SomePublicClass> dummyStatic = Mockito.mockStatic(SomePublicClass.class)) {
dummyStatic.when(() -> SomePublicClass.myPublicStaticFunc(anyInt()))
.thenReturn(5);
// when
System.out.println(SomePublicClass.myPublicStaticFunc(7));
//then
dummyStatic.verify(
times(1),
() -> SomePublicClass.myPublicStaticFunc(anyInt())
);
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是调用
verify(dummyStatic).myPublicStaticFunc(anyInt);
Run Code Online (Sandbox Code Playgroud)
但是,它抱怨类型 MockedStatic 的方法 myPublicStaticFunc(int) 未定义。
我有什么选择,或者我错过了什么。另外,我知道我可以使用 PowerMock 尝试此操作,但目前,我尝试仅使用 Mockito 来实现此操作。
我喜欢做以下的事情:
.when(
myMock.doSomething(
Matchers.eq( "1" )
)
)
.thenReturn( "1" )
.othwerwise()
.thenThrow( new IllegalArgumentException() );
Run Code Online (Sandbox Code Playgroud)
当然,otherwise()方法不存在,只是为了向您展示我想要完成的任务.
我是Mockito的新手,我试过调查这个例外但我还没有找到具体的答案.当我一起使用两个模拟时,它发生在我的代码中,这意味着我通过模拟的构造函数,另一个模拟.像这样:
...
OperationNode child = getNode(Operation.ADD);
child.insertNode(getConstantNode(getIntegerValue(2));
...
private ConstantNode getConstantNode(NumericalValue value){
ConstantNode node = Mockito.mock(ConstantNode.class);
Mockito.when(node.evaluate()).thenReturn(value);
Mockito.when(node.toString()).thenReturn(value.toString());
return node;
}
private IntegerValue getIntegerValue(int number) {
IntegerValue integerValue = Mockito.mock(IntegerValue.class);
Mockito.when(integerValue.getValue()).thenReturn(number);
Mockito.when(integerValue.toString()).thenReturn(Integer.toString(number));
return integerValue;
}
Run Code Online (Sandbox Code Playgroud)
在其中一个论坛中,我读到没有通过另一个模拟的构造函数发送模拟,因为Mockito可能会对模拟调用感到困惑,所以我尝试了以下内容:
NumericalValue value = getIntegerValue(2);
child.insertNode(getConstantNode(value));
Run Code Online (Sandbox Code Playgroud)
但无济于事.我要确保,只有方法toString()和getValue()被调用,因为只有这些方法的类了.我不明白发生了什么.
我也试过分别使用模拟,看看我做错了什么:
child.insertNode(new ConstantNode(getIntegerValue(2)));
Run Code Online (Sandbox Code Playgroud)
这非常有效.
child.insertNode(getConstantNode(new IntegerValue(2)));
Run Code Online (Sandbox Code Playgroud)
这也很好.
我有一个测试方法,其中包含以下代码段:
private void buildChainCode(List<TracedPath> lines){
for(TracedPath path : lines){
/.../
}
}
Run Code Online (Sandbox Code Playgroud)
我的单元测试代码如下所示:
public class ChainCodeUnitTest extends TestCase {
private @Mock List<TracedPath> listOfPaths;
private @Mock TracedPath tracedPath;
protected void setUp() throws Exception {
super.setUp();
MockitoAnnotations.initMocks(this);
}
public void testGetCode() {
when(listOfPaths.get(anyInt())).thenReturn(tracedPath);
ChainCode cc = new ChainCode();
cc.getCode(listOfPaths);
/.../
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在运行测试时,测试代码永远不会进入for循环.什么时候我应该指定条件,以便输入for循环?目前我已指定when(listOfPaths.get(anyInt())).thenReturn(tracedPath),但我想它从未使用过.
我正在使用simito与scalatest.使用具有值类的匹配器时,我有以下问题.
import org.scalatest.FlatSpec
import org.scalatest.mock.MockitoSugar
import org.mockito.BDDMockito._
import org.mockito.Matchers.any
case class FirstId(val value: String) extends AnyVal
case class SecondId(val value: String) extends AnyVal
trait MockedClass {
def someMethods(firstId: FirstId, secondId: SecondId): Int
}
class ValueClassSpec() extends FlatSpec with MockitoSugar {
val mockedClass = mock[MockedClass]
val secondId = SecondId("secondId")
"Matchers" should "work for value class" in {
// given
given(mockedClass.someMethods(any[FirstId], org.mockito.Matchers.eq(secondId))).willReturn(3)
// when
val result = mockedClass.someMethods(FirstId("firstId"), secondId)
// then
assert(result == 3)
}
}
Run Code Online (Sandbox Code Playgroud)
结果是:
ValueClassSpec:
Matchers
- should work …Run Code Online (Sandbox Code Playgroud) 我刚刚阅读了Android中的单元仪表测试,我想知道如何在没有任何SharedPreferencesHelper类的情况下模拟SharedPreferences,就像这里一样
我的代码是:
public class Auth {
private static SharedPreferences loggedUserData = null;
public static String getValidToken(Context context)
{
initLoggedUserPreferences(context);
String token = loggedUserData.getString(Constants.USER_TOKEN,null);
return token;
}
public static String getLoggedUser(Context context)
{
initLoggedUserPreferences(context);
String user = loggedUserData.getString(Constants.LOGGED_USERNAME,null);
return user;
}
public static void setUserCredentials(Context context, String username, String token)
{
initLoggedUserPreferences(context);
loggedUserData.edit().putString(Constants.LOGGED_USERNAME, username).commit();
loggedUserData.edit().putString(Constants.USER_TOKEN,token).commit();
}
public static HashMap<String, String> setHeaders(String username, String password)
{
HashMap<String, String> headers = new HashMap<String, String>();
String auth = username + ":" + …Run Code Online (Sandbox Code Playgroud)