For your first case, you can do:
new MockUp<A> () { private int n; @Mock public void $init(int n) { this.n = n; } @Mock public boolean isCorrect() { return n == 3; } };
And for your second example:
new MockUp<A> () { @Mock public boolean isCorrect() { return false; } };
For example, this prints false, true, false, false:
new MockUp<A> () { private int n; @Mock public void $init(int n) { this.n = n; } @Mock public boolean isCorrect() { return n == 3; } }; System.out.println(new A(2).isCorrect()); System.out.println(new A(3).isCorrect()); new MockUp<A> () { @Mock public boolean isCorrect() { return false; } }; System.out.println(new A(2).isCorrect()); System.out.println(new A(3).isCorrect());
EDIT
Following your comment, one way to mock the class only for certain values of n is to use reflection to check the value of the field:
new MockUp<A> () { @Mock public boolean isCorrect(Invocation invocation) { // Gets the invoked instance. A a = invocation.getInvokedInstance(); int n = Deencapsulation.getField(a, "n"); if (n == 3) return true; else return a.isCorrect(); } };
But it becomes a bit fragile because it depends on the name of the variable in your class A.
A maybe better alternative would be to give a package-protected getter for testing purposes in your class A: int getN() { return n; } and you don't need reflection any more.