模拟类属性Java/Android [英] Mocking class properties Java/Android

查看:57
本文介绍了模拟类属性Java/Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由某人编写的类,该类将其属性公开为公共的,而没有getter/setter.

I have a class written by somebody which exposes it properties as public without getters/setters.

现在,我想使用Android Mocking框架来模拟此类. 我不想修改class_under_test(除非需要).我知道这是一种不好的编程习惯,但是有一种方法可以模拟类似的属性

Now I want to mock this class using Android Mocking framework. I dont want to modify the class_under_test (unless required). I know its a bad programming practice, but is there a way to mock the properties like

AndroidMock.expect(myMockClass.name).andReturn('Scott');

运行测试用例时出现异常:

I get exception when I run the testcase :

java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:174)
at org.easymock.EasyMock.expect(EasyMock.java:156)
at com.google.android.testing.mocking.AndroidMock.expect(AndroidMock.java:264)
at com.akshat.test.TestPerson.testGetName(TestPerson.java:41)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)

推荐答案

为该类创建一个模拟对象,并将一个值分配给properties变量.

Create a mock object for the class and assign a value to the properties variable.

Mock mock = Mock.create(ClassName.class);
mock.property = value;

这篇关于模拟类属性Java/Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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