Issue
console error
2021-07-27 23:09:35.124 ERROR 20275 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "this.wmPort" is null
at com.wmock.info.utilities.WireMockInitializer.initialize(WireMockInitializer.java:21) ~[test-classes/:na]
on overriding the initializer
@ActiveProfiles({"test"})
public class WireMockInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private WireMockServer wireMockServer;
@Value("${wiremock.port:2222}")
private Integer wmPort;
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(wmPort));
wireMockServer.start();
configurableApplicationContext.addApplicationListener(applicationEvent -> {
if (applicationEvent instanceof ContextClosedEvent) {
wireMockServer.stop();
}
});
configurableApplicationContext.getBeanFactory()
.registerSingleton("wireMockServer", wireMockServer);
}
}
Solution
The issue is because of the initialize method.
package com.wmock.info.utilities;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "wiremock")
public class CustomConfig {
private int port;
public int getPort() {
return port;
}
}
public class WireMockInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private WireMockServer wireMockServer;
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
BindResult<CustomConfig> configProps = Binder.get(environment).bind("wiremock", CustomConfig.class);
wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(configProps.get().getPort()));
wireMockServer.start();
configurableApplicationContext.addApplicationListener(applicationEvent -> {
if (applicationEvent instanceof ContextClosedEvent) {
wireMockServer.stop();
}
});
configurableApplicationContext.getBeanFactory()
.registerSingleton("wireMockServer", wireMockServer);
}
}
Answered By - Prashanth Sams
Answer Checked By - Pedro (JavaFixing Volunteer)