Powermock не издевается над консулом - PullRequest
0 голосов
/ 15 января 2020

Это метод класса, который я хочу проверить, и я хочу смоделировать все вызовы Консула. Но всякий раз, когда я запускаю тест 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>

1 Ответ

0 голосов
/ 15 января 2020

Я не пользуюсь и не знаю клиента Consul, но ваша проблема не связана с вашими зависимостями: в основном вы должны макетировать все шаги.

Пожалуйста, возьмите следующий пример (о сборщике шаблон) только в качестве предложения и адаптируйте его к вашему случаю, заменив макет, как и где вам нужно, 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);
...