sunmingtao / sample-code

3 stars 4 forks source link

Cannot mock Resttemplate.exchange method (works in Intellij, but not on command line maven build) #311

Closed sunmingtao closed 2 years ago

sunmingtao commented 2 years ago

Prod code:


final List<String> achievement =
            restTemplate.exchange(getAchivementUrl(), HttpMethod.GET, createHttpEntity(troveSessionId), List.class).getBody();

Unit test code:


Mockito.when(
            restTemplate.exchange(
                Mockito.eq(
                    String.format(AchievementService.ACHIEVEMENT_URL_TEMPLATE, TROVE_VUE_API_HOME)),
                Mockito.any(HttpMethod.class),
                Mockito.any(HttpEntity.class),
                Mockito.any(Class.class)))
        .thenReturn(responseEntity);

Unit test runs fine in Intellij. However, when running mvn clean test on command line, showing error


ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:testCompile (default-testCompile) on project tarkine: Compilation failure
[ERROR] Failure executing groovy-eclipse compiler:
[ERROR] ----------
[ERROR] 1. ERROR in D:\workspace\tarkine\src\test\java\au\gov\nla\dlir\services\AchievementServiceTest.java (at line 83)
[ERROR]         restTemplate.exchange(
[ERROR]                      ^^^^^^^^
[ERROR] The method exchange(String, HttpMethod, HttpEntity<?>, Class<T>, Object...) in the type RestTemplate is not applicable for the arguments (String, HttpMethod, HttpEntity, Class)
[ERROR] ----------
[ERROR] 1 problem (1 error)
sunmingtao commented 2 years ago

Solution is replace Mockito.any(Class.class) with Mockito.eq(List.class)

Mockito.when(
            restTemplate.exchange(
                Mockito.eq(
                    String.format(AchievementService.ACHIEVEMENT_URL_TEMPLATE, TROVE_VUE_API_HOME)),
                Mockito.any(HttpMethod.class),
                Mockito.any(HttpEntity.class),
                    Mockito.eq(List.class)))
        .thenReturn(responseEntity);