@Test public void verificationInOrderIgnoringStubs( @Mocked final MockedClass mock, @Mocked final MockedClass mockTwo) { // Stubbings, with an invocation count constraint for later (automatic) verification: new Expectations() { { mock.getItem(1); result = "ignored"; times = 1; } }; // In tested code: mock.doSomething("a", true); mockTwo.someMethod("b"); mock.getItem(1); // Verify all invocations, except those verified implicitly through recorded invocation // count constraints. // There is no support for ignoring stubbings that were not verified in any way. // That said, note the API does not require any code duplication. new FullVerificationsInOrder() { { mock.doSomething("a", true); mockTwo.someMethod("b"); } }; }
// Equivalent to "spyingOnRealObjects", but real implementations execute only on replay. @Test // Uses of JMockit API: 7 public void dynamicPartialMocking() { final MockedClass mock = new MockedClass(); // Mocks a real object: new Expectations(mock) {}; // Optionally, you can record some invocations: new Expectations() { { mock.getSomeValue(); result = 100; } }; // When recording invocations on any mocked instance, partially mocked or not, real // implementations // are never executed, so this call would never throw an exception: new Expectations() { { mock.getItem(1); result = "an item"; } }; // Using the mock calls real methods, except for calls which match recorded expectations: mock.doSomething("one", true); mock.doSomething("two", false); assertEquals("one", mock.getItem(0)); assertEquals("an item", mock.getItem(1)); assertEquals(100, mock.getSomeValue()); // Optionally, you can verify invocations to the dynamically mocked types/objects: new Verifications() { { // when verifying invocations, real implementations are never executed mock.doSomething("one", true); mock.doSomething("two", anyBoolean); } }; }
@Test // Uses of JMockit API: 4 public void stubInvocations(@Mocked final MockedClass mock) { new Expectations() { { mock.getItem(0); result = "first"; mock.getItem(1); result = new RuntimeException(); } }; assertEquals("first", mock.getItem(0)); try { mock.getItem(1); } catch (RuntimeException ignore) { // OK } assertNull(mock.getItem(999)); }