0

Can I mock a method using JMockit in a way that it returns the argument that was passed to it?

Consider a signature like this;

public String myFunction(String abc);

I see it is possible to do this using Mockito. But is this doable in JMockit?

Community
  • 1
  • 1
ViV
  • 1,998
  • 8
  • 27
  • 54
  • You may find it easier to use JMockit's "[faking](http://jmockit.org/tutorial/Faking.html)" capabilities. However, you may want to re-examine your assumptions and figure out whether this is something you really want to do. – dcsohl Dec 12 '16 at 21:04

2 Answers2

1

The JMockit manual provides some guidance... I really suggest you read it. The construct you are looking for would probably look something like this:

@Test
public void delegatingInvocationsToACustomDelegate(@Mocked final DependencyAbc anyAbc)
{
   new Expectations() {{
      anyAbc.myFunction(any);
      result = new Delegate() {
         String aDelegateMethod(String s)
         {
            return s;
         }
      };
   }};

   // assuming doSomething() here invokes myFunction()...
   new UnitUnderTest().doSomething();
}
dcsohl
  • 7,186
  • 1
  • 26
  • 44
0

JMockit can also capture arguments:

@Test
public void testParmValue(@Mocked final Collaborator myMock) {

    // Set the test expectation.
    final String expected = "myExpectedParmValue";

    // Execute the test.
    myMock.myFunction(expected);

    // Evaluate the parameter passed to myFunction.
    new Verifications() {
        { 
            String actual;
            myMock.myFunction(actual = withCapture());

            assertEquals("The parameter passed to myFunction is incorrect", expected, actual);
        }
    };
}
user6629913
  • 180
  • 1
  • 14