Issue
Let's say I have an interface Foo
with method bar(String s)
. The only thing I want mocked is bar("test");
.
I cannot do it with static partial mocking, because I only want the bar
method mocked when "test" argument is being passed. I cannot do it with dynamic partial mocking, because this is an interface and I also do not want the implementation constructor mocked. I also cannot use interface mocking with MockUp
, because I have no ability to inject mocked instance, it is created somewhere in code.
Is there something I am missing?
Solution
Indeed, for this situation you would need to dynamically mock the classes that implement the desired interface. But this combination (@Capturing
+ dynamic mocking) is not currently supported by JMockit.
That said, if the implementation class is known and accessible to test code, then it can be done with dynamic mocking alone, as the following example test shows:
public interface Foo {
int getValue();
String bar(String s);
}
static final class FooImpl implements Foo {
private final int value;
FooImpl(int value) { this.value = value; }
public int getValue() { return value; }
public String bar(String s) { return s; }
}
@Test
public void dynamicallyMockingAllInstancesOfAClass()
{
final Foo exampleOfFoo = new FooImpl(0);
new NonStrictExpectations(FooImpl.class) {{
exampleOfFoo.bar("test"); result = "aBcc";
}};
Foo newFoo = new FooImpl(123);
assertEquals(123, newFoo.getValue());
assertEquals("aBcc", newFoo.bar("test")); // mocked
assertEquals("real one", newFoo.bar("real one")); // not mocked
}
Answered By - Rogério
Answer Checked By - Senaida (JavaFixing Volunteer)