Reputation: 41
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.
Upvotes: 4
Views: 5422
Reputation: 27677
Yes, you can use the @Injectable annotation instead of @Mocked and then each mock will be a separate instance. You can do different Expectations/Verifications on those instances.
Example from the tutorial:
@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);
}
Upvotes: 0
Reputation: 16380
This is easy to solve, and there is no need to mock the same class twice. To return different values from the same mocked method in different invocations, simply record two (or more) consecutive return values if using the "Expectations API"; if using the "Mockups API", add a first parameter of type "Invocation inv" to your mock method and then use "inv.getInvocationIndex()" to know which value should be returned (not as nice as the other option, but works fine).
For more documentation and examples, have a look at the JMockit project site, or under the "jmockit/www" dir in the full distribution.
Upvotes: 3