autoparams-spring
When testing a Spring application, you often need both of the following:
- Beans provided by the Spring IoC container
- Arbitrary test data automatically generated by AutoParams
The autoparams-spring
extension bridges these two needs, allowing you to write test methods that receive Spring-managed beans and AutoParams-generated arguments side by side.
This means you can write tests that automatically inject service components from your application context and use auto-generated test data at the same time, 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-spring</artifactId>
<version>10.1.0</version>
</dependency>
Gradle (Groovy)
For Gradle Groovy, use:
testImplementation 'io.github.autoparams:autoparams-spring:10.1.0'
Gradle (Kotlin)
For Gradle Kotlin, use:
testImplementation("io.github.autoparams:autoparams-spring:10.1.0")
@UseBeans
Annotation
Suppose your Spring application has a HelloSupplier
bean that implements the MessageSupplier
interface:
- Java
- Kotlin
public interface MessageSupplier {
String getMessage(String name);
}
interface MessageSupplier {
fun getMessage(name: String): String
}
- Java
- Kotlin
@Component
public class HelloSupplier implements MessageSupplier {
@Override
public String getMessage(String name) {
return "Hello, " + name + "!";
}
}
@Component
class HelloSupplier : MessageSupplier {
override fun getMessage(name: String): String {
return "Hello, $name!"
}
}
If you want to test how your MessageSupplier
bean behaves, you can use the @UseBeans
annotation like this:
- Java
- Kotlin
@SpringBootTest
class TestClass {
@Test
@AutoParams
@UseBeans
void testMethod(MessageSupplier service, String name) {
String message = service.getMessage(name);
assertTrue(message.startsWith("Hello"));
assertTrue(message.contains(name));
}
}
@SpringBootTest
class TestClass {
@Test
@AutoParams
@UseBeans
fun testMethod(service: MessageSupplier, name: String) {
val message: String = service.getMessage(name)
assertTrue(message.startsWith("Hello"))
assertTrue(message.contains(name))
}
}
In this test:
- The
service
parameter is automatically resolved as a Spring bean. - The
name
parameter is randomly generated by AutoParams.
This allows you to seamlessly combine real Spring components with generated test data, making your tests both concise and expressive.