java - java - How can i mock a REST Request from Spring Framework inside a method - answerstu - answerstu

java - How can i mock a REST Request from Spring Framework inside a method

I got a method which includes a REST-request(Spring-Social) and i want to mock it. The thing is that i dont know how to access the call inside it or if it is possible at all. I got Mockito and PowerMock at my disposal

  private FacebookConnectionFactory facebookFactory;

  private OAuth2Operations authOps;

  private final OAuthCredentials credentials;


  public AccessToken exchangeAuthentication(String aCode) {
    facebookFactory = getOAuthConnectionFactory();
    authOps = facebookFactory.getOAuthOperations();
    authPar = new OAuth2Parameters();

    AccessGrant grant = authOps.exchangeForAccess(aCode, credentials.getFacebookRedirectURI(), null);  // I want mock this somehow

    AccessToken token = new AccessToken();

    return token;

1 Answer

  1. Aaron- Reply


    You can use Mockito to create a mock from OAuth2Operations and stub the invocation you want:

    private OAuth2Operations authOps;

    and after stub the exchangeForAccess invocation, like this:

    when(authOps.exchangeForAccess(aCode, credentials.getFacebookRedirectURI(), null)).thenReturn(new AccessGrant());

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>