Interface GivenProvider


@ExperimentalApi public interface GivenProvider
An interface for providing instances of objects that can be injected into fields or parameters using the @Given annotation.

For example, we may want to define a custom annotation for generating numeric strings:


 @ExtendWith(InstancioExtension.class)
 class ExampleTest {

     @Test
     void example(@NumericString(length = 5) String digits) {
         // Possible value of digits: 04194
     }
 }
 

To support the above use case, first we define the @NumericString annotation:


 @Given(NumericStringProvider.class)
 @Target({ElementType.FIELD, ElementType.PARAMETER})
 @Retention(RetentionPolicy.RUNTIME)
 @interface NumericString {
     int length();
 }
 

where the NumericStringProvider can be implemented as:


 class NumericStringProvider implements GivenProvider {
     @Override
     public Object provide(ElementContext context) {
         NumericString numericString = context.getAnnotation(NumericString.class);
         return context.random().digits(numericString.length());
     }
 }
 
Since:
5.0.0
See Also:
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Interface
    Description
    static interface 
    An interface representing the context of an element (either a Field or Parameter) for which an object instance is being provided.
  • Method Summary

    Modifier and Type
    Method
    Description
    Provides an instance of an object based on the given context.
  • Method Details

    • provide

      @ExperimentalApi Object provide(GivenProvider.ElementContext context)
      Provides an instance of an object based on the given context.
      Parameters:
      context - the context containing metadata about the element (either a Field or Parameter) annotated or meta-annotated with the @Given annotation
      Returns:
      an instance of an object
      Since:
      5.0.0