Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JMockit, how do I mock an interface method for specific input parameter values?

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?

like image 282
Marcin Avatar asked Jun 04 '26 11:06

Marcin


2 Answers

Foo foo = new MockUp<Foo>() {
   @Mock
   public bar(String s)(){
      return "test";
   }
}.getMockInstance();

foo.bar("") will now return "test"...

like image 200
Jun Jiang Avatar answered Jun 07 '26 01:06

Jun Jiang


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
}
like image 20
Rogério Avatar answered Jun 07 '26 01:06

Rogério



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!