Это метод класса, который я хочу проверить, и я хочу смоделировать все вызовы Консула. Но всякий раз, когда я запускаю тест junit, я получаю сообщение об ошибке NullPointerException для конструктора Consul. Это не создавало фиктивное соединение для Consul.class. Может ли кто-нибудь мне помочь.
public Dependency checkConsulHealth(String consulUrl, String aclToken) {
try {
Consul.builder().withUrl(consulUrl).withAclToken(aclToken).build();
LOGGER.debug("Consul connection successful");
return new Dependency(consulUrl, CONSUL_SERVICE, SUCCESS_MESSAGE, SUCCESS_STATUS);
} catch (Exception exception) {
LOGGER.debug("Consul connection unsuccessful");
return new Dependency(consulUrl, CONSUL_SERVICE, ERROR_MESSAGE, ERROR_STATUS);
}
}
Это мой тестовый класс, здесь я пытаюсь проверить мой метод класса healthCheckService.
@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.orbitz.consul.Consul")
public class TestHealthCheckService {
private static final String CONSUL_URL = "Consul";
private static final String ACL_TOKEN = "123";
@InjectMocks
private HealthCheckService healthCheckService;
@Before
public void init() {
MockitoAnnotations.initMocks(Consul.class);
}
@Test
public void testCheckConsulHealth() {
PowerMockito.mockStatic(Consul.class);
Dependency dependency1 = new Dependency(CONSUL_URL, CONSUL_SERVICE, SUCCESS_MESSAGE,
SUCCESS_STATUS);
System.out.println("From mock "+Consul.builder());
PowerMockito.when(Consul.builder()
.withUrl(CONSUL_URL)
.withAclToken(ACL_TOKEN)
.build())
.thenReturn(null);
Dependency dependency2 = healthCheckService.checkConsulHealth(CONSUL_URL, ACL_TOKEN);
assertEquals(dependency1, dependency2);
}
Моя POM. xml В зависимости, где я использовал следующие зависимости
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.4</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.4</version>
<scope>test</scope>
</dependency>