Testing Twitter4J with PowerMock

582 views Asked by At

I'm trying to mock the following code using PowerMock

Twitter twitter = TwitterFactory.getSingleton();

RequestToken requestToken = twitter.getOAuthRequestToken();

Here is the start of my unit test

@RunWith(PowerMockRunner.class)
@PrepareForTest(TwitterFactory.class)
public class AuthorisationHelperTest {

    @Test
    public void testMain() throws TwitterException {
        // Arrange
        PowerMockito.mockStatic(TwitterFactory.class);
        Twitter mockTwitter = new Twitter();
        Mockito.when(TwitterFactory.getSingleton()).thenReturn(mockTwitter);

However I get an error saying I cannot instantiate the type Twitter. I figure I must be thinking about this the wrong way. Any tips?

1

There are 1 answers

0
Makoto On BEST ANSWER

Here's how you declare and instantiate a new instance of a Twitter object:

Twitter twitter = TwitterFactory.getSingleton();

If you cannot instantiate a Twitter class, the likelihood is that it has a non-visible constructor, and is only ever possible to get via the factory.

What you probably want to do is supply a mock of Twitter instead.

Twitter twitter = mock(Twitter.class);