autoparams-mockito
autoparams-mockito
is an extension of AutoParams that enables the automatic creation of test doubles for interfaces and abstract classes using Mockito, a widely used mocking framework for Java. With this extension, AutoParams can generate test doubles seamlessly—with minimal setup.
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>11.0.5</version>
</dependency>
Gradle (Groovy)
For Gradle Groovy DSL, use:
testImplementation 'io.github.autoparams:autoparams-mockito:11.0.5'
Gradle (Kotlin)
For Gradle Kotlin DSL, use:
testImplementation("io.github.autoparams:autoparams-mockito:11.0.5")
Generating Test Doubles with Mockito
Suppose you have an interface that represents a dependency:
- Java
- Kotlin
public interface Dependency {
String getName();
}
interface Dependency {
val name: String
}
And a system under test that relies on this dependency:
- Java
- Kotlin
public class SystemUnderTest {
private final Dependency dependency;
public SystemUnderTest(Dependency dependency) {
this.dependency = dependency;
}
public String getMessage() {
return "Hello " + dependency.getName();
}
}
class SystemUnderTest(private val dependency: Dependency) {
val message: String
get() = "Hello ${dependency.name}"
}
By using the @Customization(MockitoCustomizer.class)
annotation, AutoParams will automatically generate Mockito-based test doubles for eligible parameters (such as interfaces and abstract classes).
Here’s an example:
- Java
- Kotlin
@Test
@AutoParams
@Customization(MockitoCustomizer.class)
void testMethod(@Freeze Dependency stub, SystemUnderTest sut) {
when(stub.getName()).thenReturn("World");
assertEquals("Hello World", sut.getMessage());
}
@Test
@AutoKotlinParams
@Customization(MockitoCustomizer::class)
fun testMethod(@Freeze stub: Dependency, sut: SystemUnderTest) {
whenever(stub.name).thenReturn("World")
assertEquals("Hello World", sut.message)
}
In this test:
stub
is a test double automatically generated by Mockito.- The
@Freeze
annotation ensures that the samestub
instance is injected into theSystemUnderTest
. - You can configure the test double using standard Mockito syntax.
This integration streamlines test setup, enabling you to focus on verifying behavior rather than wiring dependencies manually.