No description
- Java 98.4%
- Kotlin 1.6%
| gradle/wrapper | ||
| src | ||
| .editorconfig | ||
| .gitignore | ||
| build.gradle.kts | ||
| gradlew | ||
| gradlew.bat | ||
| README.md | ||
| settings.gradle.kts | ||
Stefan's little mocking library
This mocking library was built as a weekend project. It probably doesn't do everything you'd expect from your mocking library/framework, but it's relatively simple.
Usage
Let's see if we can test a piece of code that uses the following two interfaces (though they could just as well be classes):
interface Database {
List<Integer> query() throws SQLException;
}
interface Service {
int compute(int other);
void doVoid();
}
Here's what a test could look like:
@Test
public void test() {
// Create a database mock
Mock<Database> databaseMock = Mock.createMock(Database.class);
// Create a service mock
Mock<Service> serviceMock = Mock.createMock(Service.class);
// Expect the first call to Database to return {1, 2, 3}
databaseMock.expect(Database::query).andReturn(List.of(1, 2, 3));
// Expect the next (second) call to Database to throw an exception
databaseMock.expect(Database::query).andThrow(SQLException::new);
// Expect the Service.compute method to be called with an argument of value 666,
// zero or more times, and return 0
serviceMock.expect(srv -> srv.compute(666)).anyTimes().andReturn(0);
// Expect the Service.compute method to be called twice with an argument value of 3,
// and return 9 both times
serviceMock.expect(srv -> srv.compute(3)).times(2).andAnswer(() -> 9);
// Expect the Service.compute method to be called with an argument of value 42,
// zero or more times, and return 42
serviceMock.expect(srv -> srv.compute(42)).anyTimes().andReturn(42);
// Expect the Service.doVoid method to be called
serviceMock.expectVoid(Service::doVoid);
// Verify the database mock. "db" will be passed in, which is the database mock
databaseMock.verify(db ->
// Verify the service mock. "srv" will be passed in, which is the service mock
serviceMock.verify(srv ->
assertThat(new MockTest().doSomething(db, srv), is(equalTo(81)))));
}
For completeness' sake, here's the definition of the doSomething function:
/**
* Test code that exercices the mocks.
*/
private int doSomething(Database db, Service srv) throws SQLException {
System.out.println("Compute 666: " + srv.compute(666));
System.out.println("Compute 666: " + srv.compute(666));
System.out.println("Query result: " + db.query());
try {
db.query();
} catch (SQLException e) {
System.err.println("Succesfully caught exception " + e);
}
int firstComputeResult = srv.compute(3);
int result = firstComputeResult * srv.compute(3);
srv.doVoid();
return result;
}