jmockit返回相同的对象

时间:2016-12-09 20:12:36

标签: java mocking testng jmockit

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

考虑这样的签名;

public String myFunction(String abc);

see可以使用Mockito执行此操作。但这在JMockit中是否可行?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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