0

我有一个由某人编写的类,它将其属性公开为没有 getter/setter。

现在我想使用 Android Mocking 框架来模拟这个类。我不想修改 class_under_test(除非需要)。我知道这是一种不好的编程习惯,但是有没有办法模拟像这样的属性

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

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

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)
4

2 回答 2

1

为类创建一个模拟对象并为属性变量赋值。

Mock mock = Mock.create(ClassName.class);
mock.property = value;
于 2013-06-04T18:32:13.397 回答
0

Why do you want to mock this class at all? If the only behavior is trivial (i.e. fields), then you can use the class's fields just as they are.

E.g., if setting this up as a stub, do this in your test setup:

DependedOnClass dependedOnObject = new DependedOnClass();
dependedOnObject.name = "Scott";
objectUnderTest.dependedOnObject = dependedOnObject;    // inject the depended on object

or if setting this up as a mock, then do this in your assertions:

assertEquals("Scott", dependedOnObject.name);
于 2013-03-01T16:43:01.980 回答