3

I need to write a test, where-in, the behaviour of a class can be verified, for different behaviours of a Mocked class. To support multiple behaviours for the same method, we need to mock the class multiple times, in the same TestClass.

Is it possible using JMockIt?

Here is an example of what I want. This is the main class to be tested and its test:

public class MyClass {

    private Foo fooObj = null;

    public setfooObj(Foo obj) {
        fooObj = obj;
    }

    public boolean process() {
        // uses fooObj.getName() to process 
    }
}

public class MyClassTest {

    @MockClass(realClass = mypackage.Foo.class)
    public static class MockFoo {

        @Mock
        public static boolean getName() {
            return "test";
        }
    }

    @Test
    public void validateProcessing() {
        MyClass testObj = new MyClass();
        assertEquals(false, testObj.process);
    }
}

Now, I want to verify testObj.process() method's behaviour, when MockFoo.getName() returns different values. For my first assertion, I want to use its value as "test"(as returned by the mocked function), but for the following ones, I want to check with different values.

4

2 回答 2

2

这个很容易解决,不需要mock同一个类两次。要在不同的调用中从相同的模拟方法返回不同的值,如果使用“Expectations API”,只需记录两个(或更多)连续的返回值;如果使用“Mockups API”,请将“Invocation inv”类型的第一个参数添加到您的模拟方法中,然后使用“inv.getInvocationIndex()”来知道应该返回哪个值(不像其他选项那么好,但可以美好的)。

有关更多文档和示例,请查看 JMockit 项目站点,或在完整发行版中的“jmockit/www”目录下。

于 2012-05-15T20:08:36.667 回答
0

是的,您可以使用@Injectable注释而不是@Mocked,然后每个模拟将是一个单独的实例。您可以对这些实例执行不同的期望/验证。

教程中的示例:

@Test
public void concatenateInputStreams(
  @Injectable final InputStream input1,
  @Injectable final InputStream input2)
{
  new Expectations() {{
     input1.read(); returns(1, 2, -1);
     input2.read(); returns(3, -1);
  }};

  InputStream concatenatedInput = new ConcatenatingInputStream(input1, input2);
  byte[] buf = new byte[3];
  concatenatedInput.read(buf);

  assertArrayEquals(new byte[] {1, 2, 3}, buf);
}
于 2012-06-19T09:12:12.810 回答