在没有第三方框架的情况下测试Android活动时如何注入依赖关系?

Ell*_*tus 7 android dependency-injection abstract-factory android-testing

我想测试一个CommentActivity通常构造和使用实例的Android活动CommentsDataSource(两者都是我写的类).

public class CommentActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    :
    CommentsDataSource = new CommentsDataSource(..);
    :
  }
  :
}
Run Code Online (Sandbox Code Playgroud)

我愿意创建MockCommentsDataSource自己,并希望避免使用第三方模拟框架.(为什么?因为我的教学试图减少我需要填写的学期信息量以及学生需要安装的软件数量.我看过其他帖子推荐Guice,roboguice和Spring.)

我的问题是如何将CommentsDataSource(或MockCommentsDataSource)传递给Activity.制作它们似乎不切实际,Serializable或者Parcelable它们必须是为了通过Intent它开始传递它们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));
      :
   }
   :
}
Run Code Online (Sandbox Code Playgroud)

我应该如何注入MockCommentsDataSourceCommentActivity?FWIW,我正在使用Eclipse并正在开发最新的SDK版本.

我遇到的一个解决方案是使用抽象工厂模式,因为使工厂可序列化相对容易.鉴于我的限制,这是最好的方法吗?

Omr*_*374 1

这里有两个想法:

不使用工厂:

这可能仅适用于单元测试,不适用于集成测试:

  1. 创建一个返回 CommentsDataSource 的方法,例如 getCommentsDataSource()
  2. 创建一个继承CommentActivity的类
  3. 使用返回 MockCommentsDataSource 的方法覆盖 getCommentsDataSource()
  4. 测试新类

使用工厂:

正如您所提到的,您可以更改 CommentActivity 代码以从工厂方法获取 CommentsDataSource。这样你就可以让工厂方法返回模拟类。

希望这可以帮助!