我想测试一个CommentActivity
通常构造和使用实例的 Android 活动CommentsDataSource
(两者都是我编写的类)。
public class CommentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
:
CommentsDataSource = new CommentsDataSource(..);
:
}
:
}
我愿意创建MockCommentsDataSource
自己,并希望避免使用第三方模拟框架。(为什么?因为我是一名教师,试图减少我需要在学期中填满的信息量以及我的学生需要安装的软件数量。我看过其他推荐 Guice、roboguice 和 Spring 的帖子。)
我的问题是如何将CommentsDataSource
(或MockCommentsDataSource
)传递给活动。Serializable
制作它们或似乎不切实际Parcelable
,它们必须是它们才能通过Intent
that 开始传递CommentActivity
。虽然我可以轻松地传入调试标志,但使用它需要CommentActivity
了解MockCommentsDataSource
,这实际上与它无关(并且在单独的应用程序中):
public class CommentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
:
debugMode = getIntent().getBooleanExtra(DEBUG_MODE, false);
// Get a connection to the database.
final CommentsDataSource cds = (debugMode ?
new MockCommentsDataSource() : // Abstraction violation
new CommentsDataSource(this));
:
}
:
}
我应该如何MockCommentsDataSource
注入CommentActivity
?FWIW,我正在使用 Eclipse 并正在为最新的 SDK 版本进行开发。
我想到的一种解决方案是使用抽象工厂模式,因为使工厂可序列化相对容易。考虑到我的限制,这是最好的方法吗?