Mockito - 覆盖采用原始参数的方法 [英] Mockito - Overriding a method that takes primitive parameters

查看:415
本文介绍了Mockito - 覆盖采用原始参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它是 Context 的子类。我正在对另一个依赖于这个类的类进行单元测试,因此我嘲笑它。但是,我需要一些方法来充当它们的原始行为,因此我将取消它们。

I have a class which is subclass of Context. I'm unit-testing another class which have dependency to this class, and therefore I've mocked it. However, I need some methods to act as their original behavior, so I'm going to "unmock" them.

其中一个是 getAssets ()所以我写了这个并且它正常工作:

One of them is getAssets() so I wrote this and it works correctly:

Mockito.doReturn(this.getContext().getAssets()).when(keyboard).getAssets();

keyboard 是该类的模拟实例提到。

keyboard is the mocked instance of the class mentioned.

由于此方法不带参数,因此覆盖它非常简单。

Since this method takes no parameters, overriding it was pretty simple.

我还需要覆盖 Context.getString(int)也是。该参数使事情变得困难,而且它变得更原始,更加困难。

I also need to override Context.getString(int) too. The parameter makes things difficult and it being a primitive, makes even more difficult.

我拿了这个建议和另一个,并尝试编写此代码:

I took this advice and another one, and tried writing this code:

Mockito.when(keyboard.getString(Mockito.anyInt())).thenAnswer(new Answer<String>(){
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable
         Integer arg = (Integer)invocation.getArguments()[0];
         return OuterClass.this.getContext().getString(arg.intValue());
    }
});

这是编译并执行的,但给出了以下例外:

This compiled and executed, but gave the following exception:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at [...] <The code above>

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

at android.content.Context.getString(Context.java:282)
at [...]
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:545)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)

所以主要问题是如何覆盖方法Mockito,有原始参数?

So the main question is How to override methods in Mockito, which have primitive parameters?

提前致谢

推荐答案

你不能存根 getString 因为它是最终的。 Mockito不能存在最终方法。只需将其保留为未打印状态,即可获得原始实现。这就是你想要的,对吗?

You can't stub getString because it's final. Mockito can't stub final methods. Just leave it unstubbed, and you'll get its original implementation. That's what you want anyway, right?

这篇关于Mockito - 覆盖采用原始参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆