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>8.3.0</version>
</dependency>
Gradle
For Gradle, use:
testImplementation 'io.github.autoparams:autoparams-mockito:8.3.0'
Generating Test Doubles with Mockito
Consider a situation where you have an interface that abstracts certain services:
- Java
- Kotlin
public interface Dependency {
String getName();
}
interface Dependency {
val name: String
}
You also have a system that relies on this Dependency
interface:
- 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
}
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:
- Java
- Kotlin
@ParameterizedTest
@AutoSource
@Customization(MockitoCustomizer.class)
void testUsingMockito(@Freeze Dependency stub, SystemUnderTest sut) {
when(stub.getName()).thenReturn("World");
assertEquals("Hello World", sut.getMessage());
}
import org.mockito.kotlin.whenever
@ParameterizedTest
@AutoSource
@Customization(MockitoCustomizer::class)
fun testUsingMockito(@Freeze stub: Dependency, sut: SystemUnderTest) {
whenever(stub.name).thenReturn("World")
assertEquals("Hello World", sut.message)
}
In the above example:
- The
stub
argument is a mock generated by Mockito, thanks to theMockitoCustomizer
. - The
@Freeze
annotation ensures that this mock object (stub
) is reused as a parameter for the construction of theSystemUnderTest
object (sut
).
This integration simplifies the creation of mock objects for parameterized tests, making testing more efficient and straightforward.