Skip to content

Instantly share code, notes, and snippets.

@KidA78 KidA78/gist:5279210

Created Mar 31, 2013
What would you like to do?
Some code to help engineers mock Twitter4J using EasyMock
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
import org.easymock.IExpectationSetters;
import org.json.JSONArray;
import org.json.JSONObject;
import twitter4j.Paging;
import twitter4j.RateLimitStatus;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.json.DataObjectFactory;
import com.mycompany.MyService;
import com.mycompany.MyResponse;
public class TestTwitter4J {
MyService myService;
* Builds a Twitter Status Timeline Response given a raw JSON String
* @param twitterRawJSONResponse, a user defined JSON String containing tweets
* @return A {@link ResponseList} containing expected tweets
* @throws Exception
public static ResponseList<Status> buildUserTimelineResponseList(String twitterRawJSONResponse) throws Exception {
ResponseList<Status> responseList = null;
JSONArray array = new JSONArray(twitterRawJSONResponse);
final List<Status> list = new ArrayList<Status>();
if (array.length() > 0) {
for (int x = 0; x < array.length(); x++) {
JSONObject obj = (JSONObject) array.get(x);
Status status = DataObjectFactory.createStatus(obj.toString());
// Create a mock {@link ResponseList} that returns the statuses constructed
// Only mock the toArray method, only one being used
responseList = EasyMock.createMock(ResponseList.class);
return responseList;
* Creates a Mock Twitter service, taking an array of JSON responses to
* recreate the order in which statuses are returned from Twitter
* @param twitterJSONResponses
* @return
* @throws Exception
public static Twitter buildMockTwitterService(String[] twitterJSONResponses) throws Exception {
Twitter ret = EasyMock.createMock(Twitter.class);
IExpectationSetters<ResponseList<Status>> expectation = EasyMock.expect(ret.getUserTimeline(EasyMock.isA(String.class),
for (String resp : twitterJSONResponses) {
return ret;
public void testMyApp() {
String [] expectedTweetJsons = new String[] { SOME_STATIC_JSON1, SOME_STATIC_JSON2 }
Twitter mockTwitter = buildMockTwitterService(expectedTweetJsons);
// Now Twitter4J can work behind the scenes!
MyResponse res = myService.processUserTimeline();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.