Skip to main content
Version: 9.x

autoparams-mockito

autoparams-mockito is an extension of the AutoParams library that facilitates the creation of mocks for interfaces and abstract classes using Mockito, a popular mocking framework in Java. By integrating these two libraries, you can seamlessly generate mock objects for your tests.

Install​

Maven​

For Maven, you can add the following dependency to your pom.xml:

<dependency>
<groupId>io.github.autoparams</groupId>
<artifactId>autoparams-mockito</artifactId>
<version>9.0.0</version>
</dependency>

Gradle (Groovy)​

For Gradle Groovy DSL, use:

testImplementation 'io.github.autoparams:autoparams-mockito:9.0.0'

Gradle (Kotlin)​

For Gradle Kotlin DSL, use:

testImplementation("io.github.autoparams:autoparams-mockito:9.0.0")

Generating Test Doubles with Mockito​

Consider a situation where you have an interface that abstracts certain services:

public interface Dependency {

String getName();
}

You also have a system that relies on this Dependency interface:

public class SystemUnderTest {

private final Dependency dependency;

public SystemUnderTest(Dependency dependency) {
this.dependency = dependency;
}

public String getMessage() {
return "Hello " + dependency.getName();
}
}

To generate mock objects for interfaces or abstract classes, the autoparams-mockito extension provides the MockitoCustomizer. When you decorate your test method with @Customization(MockitoCustomizer.class), the @AutoSource annotation will employ Mockito to create mock values for the specified parameters.

Here's how you can apply this in practice:

@ParameterizedTest
@AutoSource
@Customization(MockitoCustomizer.class)
void testUsingMockito(@Freeze Dependency stub, SystemUnderTest sut) {
when(stub.getName()).thenReturn("World");
assertEquals("Hello World", sut.getMessage());
}

In the above example:

  • The stub argument is a mock generated by Mockito, thanks to the MockitoCustomizer.
  • The @Freeze annotation ensures that this mock object (stub) is reused as a parameter for the construction of the SystemUnderTest object (sut).

This integration simplifies the creation of mock objects for parameterized tests, making testing more efficient and straightforward.