Hi I am trying to initialize a field with @PostConstruct method but in tests, this method does not fill the bidiMap field.
Is there any way to mock bidiMap field which is a field of DataSource ?
@Component
@Getter
@Setter
@NoArgsConstructor
public class DataSource {
public DualHashBidiMap<String, String> bidiMap = new DualHashBidiMap();
@PostConstruct
public void loadData() throws IOException {
Map<String, String> data = new ObjectMapper().readValue(new File("src/main/resources/static/data.json"), Map.class);
data.entrySet().stream().forEach(item -> this.bidiMap.put(item.getKey(), item.getValue()));
}
}
Test:
@Test
void shouldReturnPrettifiedUrl_WithQueryParams() throws IOException {
// Given
List<String> inputParameters = Arrays.asList("/products?gender=female&tag=123&tag=1234");
HashMap<String, String> expectedResult = PrettyUrlResponseBuilder.PrettyUrlResponseBuilder().createPrettyUrlResponseWithParams();
HashMap<String, String> databaseResponse = DatabaseResponse.DatabaseResponse().createDatabaseResponse();
System.out.println(dataSource);
// When
Map<String, String> actualResult = prettyUrlService.toPretty(inputParameters);
// Then
assertEquals(expectedResult, actualResult);
}
The class being tested:
@Service
public class PrettyUrlService {
private final DataSource dataSource;
public PrettyUrlService(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, String> toPretty(List<String> urlList) throws IOException {
var data = dataSource.getBidiMap(); // Here, data is null.
// ...
}
}