Created
December 24, 2011 12:03
-
-
Save froop/1517213 to your computer and use it in GitHub Desktop.
[Java] WebアプリにLoginしてDownloadするTest
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
| import static org.junit.Assert.*; | |
| import java.io.BufferedReader; | |
| import java.io.IOException; | |
| import java.io.InputStreamReader; | |
| import java.io.PrintStream; | |
| import java.net.CookieHandler; | |
| import java.net.CookieManager; | |
| import java.net.CookiePolicy; | |
| import java.net.HttpURLConnection; | |
| import java.net.MalformedURLException; | |
| import java.net.URL; | |
| import org.junit.After; | |
| import org.junit.Before; | |
| import org.junit.Test; | |
| public class DownloadTest { | |
| private static final String BASE_URL = "http://localhost:8080/"; | |
| private CookieManager cookie; | |
| @Before | |
| public void setUp() throws Exception { | |
| cookie = new CookieManager(); | |
| cookie.setCookiePolicy(CookiePolicy.ACCEPT_ALL); | |
| CookieHandler.setDefault(cookie); | |
| login(); | |
| } | |
| @After | |
| public void tearDown() throws Exception { | |
| logout(); | |
| } | |
| @Test | |
| public void testDownload() throws Exception { | |
| HttpURLConnection con = openHttpURLConnection("download"); | |
| assertEquals(200, con.getResponseCode()); | |
| assertEquals("filename=\"test.csv\"", | |
| con.getHeaderField("Content-Disposition")); | |
| BufferedReader reader = new BufferedReader(new InputStreamReader( | |
| con.getInputStream())); | |
| assertEquals("Test download", reader.readLine()); | |
| reader.close(); | |
| } | |
| private void login() throws IOException, MalformedURLException { | |
| HttpURLConnection con = openHttpURLConnection("login"); | |
| con.setDoOutput(true); | |
| PrintStream out = new PrintStream(con.getOutputStream()); | |
| out.print("user=testuser&password=testpass"); | |
| out.close(); | |
| assertEquals(200, con.getResponseCode()); | |
| // System.out.println(cookie.getCookieStore().getCookies()); | |
| } | |
| private void logout() throws IOException, MalformedURLException { | |
| HttpURLConnection con = openHttpURLConnection("logout"); | |
| assertEquals(200, con.getResponseCode()); | |
| } | |
| private HttpURLConnection openHttpURLConnection(String url) | |
| throws IOException, MalformedURLException { | |
| return (HttpURLConnection) new URL(BASE_URL + url).openConnection(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment