2

我对 JMockit 很陌生,我正在尝试找到一种方法来做一些我不能做或我不明白如何形成文档的事情。在 Mockito 中相当容易。

我有许多真正的具体类,它们返回其接口引用的实例。例如:

final IAmAnInterface interf = 
    someRealClass.createMeAnInterfaceInstance(param1, param2, param3)

我想模拟实现 interf out 的方法之一,以便它做一些特定的事情,但只是在测试用例的后期,例如,如果我处理的是类而不是我会使用的接口:

new Mockup<ConcreteClassOfIAmAnInterface>() {
    @Mock
    int someMethod() throws SomeException {
        return 1+2+3+4+5; // my special value
    }
}

如果我知道someRealClass 会返回什么效果很好,但是如果我用“IAmAnInterface”替换“ConcreteClassOfIAmAnInterface”,那么该方法就不会被模拟。

如果我要使用 Mockito,我会做类似的事情:

final IAmAnInterface mock = spy(interf);
when(mock.someMethod()).thenReturn(1+2+3+4+5);

在 JMockit 中是否有一个不错的方法/任何方法可以做到这一点?

4

1 回答 1

4

您尝试使用“JMockit Mockups”API,它与典型的模拟 API 非常不同。

相反,使用更熟悉的“JMockit Expectations & Verifications”API:

@Test // note the "mock parameter" below (or declare a mock field)
public void regularTest(@Mocked final IAmAnInterface mock)
{
    // Record expectations if/as needed:
    new NonStrictExpectations() {{
        mock.someMethod(); result = 123;
    }};

    // Use the mock object in the SUT.
    ...

    // Verify expectations if/as needed:
    new Verifications() {{ mock.doSomething(); }};
}

@Test // this is the equivalent to a Mockito "spy"
public void testUsingPartialMocking()
{
   final IAmAnInterface realObject = new SomeImplementation();

   new NonStrictExpectations(realObject) {{
      // Record zero or more expectations.
      // Calls to "realObject" *not* recorded here will execute real code.
   }};

   // call the SUT

   // verify expectations, if any
}
于 2012-08-22T18:07:06.453 回答