由于该方法位于要扩展的类中,因此它变得有些问题。有几个问题需要考虑:getApplicationContext
- 你真的不能模拟一个正在测试的类,这是对象继承(即子类化)的众多缺点之一。
- 另一个问题是
,ApplicationContext
是一个单例,这使得测试变得更加邪恶,因为你不能轻易地模拟出一个被编程为不可替代的全局状态。
在这种情况下,您可以做的是优先选择对象组合而不是继承。因此,为了使您的可测试性,您需要稍微拆分一下逻辑。假设您的叫 .它需要由逻辑组件(或类)组成,让我们将其命名为。下面是一个简单的类图:Activity
Activity
MyActivity
MyActivityLogic

为了解决单例问题,我们让逻辑与应用程序上下文“注入”,以便可以用模拟来测试它。然后,我们只需要测试对象是否已将正确的应用程序上下文放入 。我们基本上如何解决这两个问题是通过另一层抽象(转述自巴特勒·兰普森)。在本例中添加的新层是移动到活动对象外部的活动逻辑。MyActivity
MyActivityLogic
为了您的示例,这些类需要看起来像这样:
public final class MyActivityLogic {
private MyApp mMyApp;
public MyActivityLogic(MyApp pMyApp) {
mMyApp = pMyApp;
}
public MyApp getMyApp() {
return mMyApp;
}
public void onClick(View pView) {
getMyApp().setNewState();
}
}
public final class MyActivity extends Activity {
// The activity logic is in mLogic
private final MyActivityLogic mLogic;
// Logic is created in constructor
public MyActivity() {
super();
mLogic = new MyActivityLogic(
(MyApp) getApplicationContext());
}
// Getter, you could make a setter as well, but I leave
// that as an exercise for you
public MyActivityLogic getMyActivityLogic() {
return mLogic;
}
// The method to be tested
public void onClick(View pView) {
mLogic.onClick(pView);
}
// Surely you have other code here...
}
它应该看起来像这样:
要进行测试,您只需要一个简单的jUnit而不是(因为它不是活动),并且您可以使用您选择的模拟框架来模拟应用程序上下文(因为手动滚动自己的模拟有点拖累)。示例使用Mockito:MyActivityLogic
TestCase
ActivityUnitTestCase
MyActivityLogic mLogic; // The CUT, Component Under Test
MyApplication mMyApplication; // Will be mocked
protected void setUp() {
// Create the mock using mockito.
mMyApplication = mock(MyApplication.class);
// "Inject" the mock into the CUT
mLogic = new MyActivityLogic(mMyApplication);
}
public void testOnClickShouldSetNewStateOnAppContext() {
// Test composed of the three A's
// ARRANGE: Most stuff is already done in setUp
// ACT: Do the test by calling the logic
mLogic.onClick(null);
// ASSERT: Make sure the application.setNewState is called
verify(mMyApplication).setNewState();
}
要像往常一样测试您使用的,我们只需要确保它创建具有正确.粗略的测试代码示例,可以完成所有这些操作:MyActivity
ActivityUnitTestCase
MyActivityLogic
ApplicationContext
// ARRANGE:
MyActivity vMyActivity = getActivity();
MyApp expectedAppContext = vMyActivity.getApplicationContext();
// ACT:
// No need to "act" much since MyActivityLogic object is created in the
// constructor of the activity
MyActivityLogic vLogic = vMyActivity.getMyActivityLogic();
// ASSERT: Make sure the same ApplicationContext singleton is inside
// the MyActivityLogic object
MyApp actualAppContext = vLogic.getMyApp();
assertSame(expectedAppContext, actualAppContext);
希望这一切都对你有意义,并帮助你。