|
| 1 | +package org.example; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import org.junit.jupiter.api.extension.ExtensionContext; |
| 6 | +import org.junit.jupiter.api.extension.ParameterContext; |
| 7 | +import org.junit.jupiter.api.extension.ParameterResolutionException; |
| 8 | +import org.junit.jupiter.api.extension.ParameterResolver; |
| 9 | + |
| 10 | +import java.io.BufferedReader; |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.InputStream; |
| 13 | +import java.io.InputStreamReader; |
| 14 | + |
| 15 | +public class FixtureParameterResolver implements ParameterResolver { |
| 16 | + |
| 17 | + public static final String BASE_PATH = "/fixtures/%s"; |
| 18 | + private static final ObjectMapper objectMapper = new ObjectMapper(); |
| 19 | + |
| 20 | + @Override |
| 21 | + public boolean supportsParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) |
| 22 | + throws ParameterResolutionException { |
| 23 | + return parameterContext.getParameter().isAnnotationPresent(Fixture.class); |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public Object resolveParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) |
| 28 | + throws ParameterResolutionException { |
| 29 | + Fixture fixture = parameterContext.getParameter().getAnnotation(Fixture.class); |
| 30 | + |
| 31 | + final String fileName = fixture.value(); |
| 32 | + final String filePath = String.format(BASE_PATH, fileName); |
| 33 | + final InputStream inputStream = FixtureParameterResolver.class.getResourceAsStream(filePath); |
| 34 | + |
| 35 | + final String data; |
| 36 | + |
| 37 | + try { |
| 38 | + data = readFromInputStream(inputStream); |
| 39 | + } catch (IOException ex) { |
| 40 | + throw new ParameterResolutionException(ex.getMessage(), ex); |
| 41 | + } |
| 42 | + |
| 43 | + if (parameterContext.getParameter().getType().isAssignableFrom(String.class)) { |
| 44 | + return data.trim(); |
| 45 | + } |
| 46 | + |
| 47 | + try { |
| 48 | + return objectMapper.readValue(data, parameterContext.getParameter().getType()); |
| 49 | + } catch (JsonProcessingException e) { |
| 50 | + throw new ParameterResolutionException(e.getMessage(), e); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private String readFromInputStream(final InputStream inputStream) |
| 55 | + throws IOException { |
| 56 | + final StringBuilder resultStringBuilder = new StringBuilder(); |
| 57 | + |
| 58 | + try (final BufferedReader br |
| 59 | + = new BufferedReader(new InputStreamReader(inputStream))) { |
| 60 | + String line; |
| 61 | + while ((line = br.readLine()) != null) { |
| 62 | + resultStringBuilder.append(line).append("\n"); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return resultStringBuilder.toString(); |
| 67 | + } |
| 68 | +} |
0 commit comments