jmockit return 同一个对象

jmockit return the same object

我可以使用 JMockit 模拟一个方法,使其 returns 传递给它的参数吗?

考虑这样的签名;

public String myFunction(String abc);

see 使用 Mockito 可以做到这一点。但这在 JMockit 中可行吗?

JMockit也可以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);
        }
    };
}

JMockit manual 提供了一些指导...我真的建议您阅读它。您正在寻找的构造可能看起来像这样:

@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();
}