这是一个我想测试的类方法,我想模拟所有的Consul调用。但是,每当我作为junit测试运行时,我都会收到Consul builder的NullPointerException错误。它没有为Consul.class .Can创建模拟连接任何人帮助我。
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>发布于 2020-01-15 13:32:43
我不使用也不知道Consul client,但您的问题与您的依赖关系无关:基本上,您必须模拟所有步骤。
请将以下示例(关于构建器模式)仅作为建议,并根据您的情况对其进行调整,在需要时随时随地用PowerMockito替换模拟:
Foo f = mock(Foo.class);
FooBuilder b = mock(FooBuilder.class);
when(b.enableAlpha()).thenReturn(b);
when(b.disableBeta()).thenReturn(b);
when(b.increaseGamma()).thenReturn(b);
when(b.build()).thenReturn(f);https://stackoverflow.com/questions/59745139
复制相似问题