Created
September 25, 2016 12:08
-
-
Save dherges/a2fa347259d7dfb4d7da064ec748c0da to your computer and use it in GitHub Desktop.
ok-testing-reloaded-medium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RetweetsIdRoute implements Route { | |
@Override | |
public Object handle(Request request, Response response) throws Exception { | |
final String idParam = request.params(":id"); | |
final String count = request.queryParams("count"); | |
final List<Tweet> tweetList = fetchTweets( | |
Long.valueOf(idParam), | |
Integer.valueOf(count != null && count.length() > 0 ? count : "100") | |
); | |
final Moshi moshi = new Moshi.Builder() | |
.add(Date.class, new DateJsonAdapter("EEE MMM dd kk:mm:ss z yyyy").nullSafe()) | |
.build(); | |
response.header("Content-Type", "application/json"); | |
return moshi.adapter(List.class).nullSafe().toJson(tweetList); | |
} | |
private List<Tweet> fetchTweets(long id, int count) { | |
final List<Tweet> tweets = new ArrayList<Tweet>(count); | |
for (int i = 0; i < count; i++) { | |
final Tweet tweet = new Tweet(); | |
tweet.id = id + i; | |
tweet.text = String.format("Retweet #%s of %s for %s", i, count, id); | |
tweet.favorited = i % 2 == 0; | |
tweets.add(tweet); | |
} | |
return tweets; | |
} | |
public static Route create() { | |
return new RetweetsIdRoute(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TwitterApp implements SparkApplication { | |
@Override | |
public void init() { | |
get("statuses/retweets/:id", RetweetsIdRoute.create()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RunWith(SparkRunner.class) | |
@SparkApplicationTest(value = TwitterApp.class, port = 4444) | |
public class TwitterAppTest { | |
@Test | |
public void test() throws IOException { | |
final OkHttpClient okHttpClient = new OkHttpClient.Builder().build(); | |
final Request request = new Request.Builder() | |
.get() | |
.url("http://localhost:4444/statuses/retweets/123") | |
.build(); | |
final Response response = okHttpClient.newCall(request).execute(); | |
assertThat(response.body().string()).startsWith("[{\"favorited\":true,\"id\":123"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment