Mockito and Spring RestTemplate issue

I want to test this class :

public class TokenIntrospector {

    private RestTemplate restTemplate;
    private String userInfoUri = "http://localhost";

    public TokenIntrospector(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String introspect(String data) {
        var userinfo = findUserInfo(data);
        return userinfo.name();
    }

    private UserInfo findUserInfo(String token) {

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.set("Accept", "application/json");
        headers.set("Authorization", format("Bearer %s", token));

        var userinfoRequest = new HttpEntity<UserInfo>(headers);

        var userinfo = restTemplate.exchange(userInfoUri,
                HttpMethod.GET,
                userinfoRequest,
                UserInfo.class);

        return userinfo.getBody();
    }
}

The issue comes from this line :

restTemplate.exchange(userInfoUri,
                    HttpMethod.GET,
                    userinfoRequest,
                    UserInfo.class);

It is calling this method (in Spring code) :

public <T> ResponseEntity<T> exchange(String url, HttpMethod method,
            @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
            throws RestClientException {

        RequestCallback requestCallback = httpEntityCallback(requestEntity, responseType);
        ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType);
        return nonNull(execute(url, method, requestCallback, responseExtractor, uriVariables));
    }

Here is my test code :

@ExtendWith(MockitoExtension.class)
public class TokenIntrospectorTest {

    @InjectMocks
    private TokenIntrospector tokenIntrospector;

    @Mock
    RestTemplate restTemplate;

    @Test
    public void test() {

        when(restTemplate.exchange(
                anyString(),
                any(HttpMethod.class),
                any(HttpEntity.class),
                any(Class.class),
                Optional.ofNullable(any()))
        ).thenReturn(ResponseEntity.ok(new UserInfo(
                "a")));

        String introspect = tokenIntrospector.introspect("data");

    }
}

Here is the error I got :

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'exchange' method:
    restTemplate.exchange(
    "http://localhost",
    GET,
    <[Accept:"application/json", Authorization:"Bearer data"]>,
    class com.example.UserInfo
);
    -> at com.example.TokenIntrospector.findUserInfo(TokenIntrospector.java:35)
 - has following stubbing(s) with different arguments:
    1. restTemplate.exchange(
    "",
    null,
    null,
    null,
    Optional.empty
);
      -> at com.example.TokenIntrospectorTest.test(TokenIntrospectorTest.java:32)
Typically, stubbing argument mismatch indicates user mistake when writing tests.

5

Optional.ofNullable(any()) does not make sense. If you stub a method call, you can either use direct arguments or only argument matchers. Optinnal.ofNullable(any()) is not a matcher and equivalent to Optional.empty() (but it will pollute Mockito’s argument matching stack).
So maybe you wanted to say any(Optional.class) or eq(Optional.empty())?

That said, your code is only passing 4 arguments to the exchange method, so you must stub the call with 4 arguments and not the call with 5 arguments:

when(
    restTemplate.exchange(
        eq("http://localhost),
        eq(HttpMethod.GET),
        any(HttpEntity.class),
        eq(UserInfo.class))
    .thenReturn(…);

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật