

There is a system model for an auction system with 2 types of policies
We want to unit test Auction, which is the SUT
The mock object test pattern is based on the idea to replace the interaction with the collaborators in the system model, that is Person, BiddingPolicy and TimingPolicy, by mock objects
These mock objects are created at startup time
A mock object replaces the behavior of a real object called the collaborator and returns hard-coded values
A mock object can be created at startup time with the factory pattern
Mock objects can be used for testing the state of individual objects and the interaction between objects
The use of mock objects is based on the record play metaphor

Open source testing framework for Java
Uses annotations for test subjects (=SUT) and mocks
@TestSubject
private ClassUnderTest classUnderTest = new ClassUnderTest();
@Mock
private Collaborator mock;
Specification of the behavior
expect(mock.invoke(parameter)).andReturn(42);
Make the mock ready to play
replay(mock);
Make sure the mock has actually been called in the test (additional assertion)
verify(mock);
@ExtendWith(EasyMockExtension.class)
class EnrollmentServiceTest {
@TestSubject // Instantiate the SUT
private EnrollmentService enrollmentService = new EnrollmentService();
@Mock // Create the mock object
private Course courseMock;
@Test
void testEnrollStudentSuccessful() {
Student student = new Student();
int expectedSize = student.getCourses().size() + 1; // Specify the expected behavior
expect(courseMock.enroll(student)).andReturn(true);
replay(courseMock); // Make the mock object ready to play
enrollmentService.enroll(student, courseMock); // Execute the SUT
assertEquals(expectedSize, student.getCourses().size()); // Validate observed against expected behavior
verify(courseMock); //Verify that enroll() was invoked on courseMock once
}
}