Reputation: 264
I'm trying to use JMockit for unit testing Android apps. It is a little bit tricky since executing the test in the local JVM means that all Android classes are stubs, but you can mock them and that's not a problem.
But now I want to test a method in a nested class that is a subclass of a ResultReceiver. This class is nested in a Fragment. The problem is that when I create this nested class, I want to mock its constructor since it will raise an exception (its is a stub). I have tried to isolate the code and the problem is not with Android but with the class structure. Example:
Base class:
public class JM_base {
int m_i;
public JM_base(int i) {
m_i = i;
}
}
Nested class:
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!");
}
}
}
The 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();
}
}
As far as I understand, the "real" constructor of Nested() should never be called, and "Hi!" should appear in the console, right ? What am I doing wrong ?
Thx
Upvotes: 2
Views: 2329
Reputation: 16380
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!");
}
Upvotes: 3