2

我正在尝试使用 JMockit 对 Android 应用程序进行单元测试。这有点棘手,因为在本地 JVM 中执行测试意味着所有 Android 类都是存根,但您可以模拟它们,这不是问题。

但现在我想在嵌套类中测试一个方法,该类是 ResultReceiver 的子类。这个类嵌套在一个片段中。问题是当我创建这个嵌套类时,我想模拟它的构造函数,因为它会引发异常(它是一个存根)。我试图隔离代码,问题不在于Android,而在于类结构。例子:

基类:

public class JM_base {
  int m_i;

  public JM_base(int i) {
    m_i = i;
  }
}

嵌套类:

public class JM_nested_class_cons {
  public class Nested extends JM_base {
    public Nested(int i) {
      super(i);
    }
    public void methodToTest() {
      System.out.print("System under test!");
    }
  }
}

考试:

public class Test_JM_nested_class_cons {
  @Mocked JM_nested_class_cons mock;

  @Test
  public void test() {
    new MockUp<JM_nested_class_cons.Nested>() {
      @Mock public void $init(int i) {
        System.out.println("Hi!");
      }
    };

    JM_nested_class_cons.Nested t = mock.new Nested(1);
    t.methodToTest();
  }
}

据我了解,永远不应调用 Nested() 的“真实”构造函数,并且“嗨!” 应该出现在控制台中,对吧?我究竟做错了什么 ?

谢谢

4

1 回答 1

3

The problem here is that MockUp treats JM_nested_class_cons.Nested as a regular, non-inner, class. So, it's not taking into account that each constructor has a hidden first parameter for the outer object (JM_nested_class_cons).

A work-around is to explicitly declare this extra parameter in the @Mock method for the constructor of the inner class:

@Mock
void $init(JM_nested_class_cons outer, int i) {
    System.out.println("Hi!");
}
于 2013-11-03T14:01:12.383 回答