【发布时间】:2013-06-27 16:31:24
【问题描述】:
我有一个 Android 活动,其中有类似的调用
final ConnectToServerAsyncTask task = new ConnectToServerAsyncTask(...);
和
final Intent intent = new Intent(this, SomeActivity.class);
为了对这个类进行单元测试,我需要能够模拟 ConnectToServerAsyncTask 和 Intent 的创建(例如使用 Mockito)。
还有比下面描述的更优雅的方法吗?
public class MainActivityOfTheApp extends Activity {
private IAsyncTaskFactory asyncTaskFactory = new AsyncTaskFactory();
private IIntentFactory intentFactory = new IntentFactory();
public void setAsyncTaskFactory(final IAsyncTaskFactory aFactory)
{
asyncTaskFactory = aFactory;
}
public void setIntentFactory(final IIntentFactory aFactory)
{
intentFactory = aFactory;
}
@Override
protected void onResume() {
...
final ConnectToServerAsyncTask task = asyncTaskFactory.create(...);
...
final Intent intent = intentFactory.create(this, OtherActivity.class);
...
}
}
在单元测试中,我会创建一个 MainActivityOfTheApp 实例,然后使用 setAsyncTaskFactory 和 setIntentFactory 注入模拟。
【问题讨论】:
-
你的解决方案也是我能想到的最聪明的。我也很想知道是否有其他方法。
标签: java android unit-testing mocking mockito