-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathRandomParametersExtension.java
69 lines (60 loc) · 2.37 KB
/
RandomParametersExtension.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* Copyright 2015-2025 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package com.example.random;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Parameter;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
/**
* {@code RandomParametersExtension} showcases the {@link ParameterResolver}
* extension API of JUnit 5 by providing injection support for random values at the
* method parameter level.
*
* <p>For real world use cases for this and other extension points, check out
* the extensions provided by the Spring and Mockito projects among others.
*
* <p>Please refer to the
* <a href="https://github.com/junit-team/junit5/wiki/Third-party-Extensions">
* Third-party Extensions wiki page</a> for additional references.
*
* @since 5.2
*/
public class RandomParametersExtension implements ParameterResolver {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Random {
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return parameterContext.isAnnotated(Random.class);
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return getRandomValue(parameterContext.getParameter(), extensionContext);
}
private Object getRandomValue(Parameter parameter, ExtensionContext extensionContext) {
Class<?> type = parameter.getType();
java.util.Random random = extensionContext.getRoot().getStore(Namespace.GLOBAL)//
.getOrComputeIfAbsent(java.util.Random.class);
if (int.class.equals(type)) {
return random.nextInt();
}
if (double.class.equals(type)) {
return random.nextDouble();
}
throw new ParameterResolutionException("No random generator implemented for " + type);
}
}