利用stub技术进行单元测试
生活随笔
收集整理的這篇文章主要介紹了
利用stub技术进行单元测试
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
待測試類:WebClient:
import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;public class WebClient {/*測試時的幾個要點:1.這個方法有兩個出口:a.正常情況下,返回從服務器發回來的數據b.如果getInputStream出錯,返回一個nullc.如果read出錯,則返回一個null*/public String getContent (URL url){StringBuffer content = new StringBuffer();try{HttpURLConnection connection = (HttpURLConnection)url.openConnection();connection.setDoInput(true);InputStream in = connection.getInputStream();byte[] buffer = new byte[2048];int count;while (-1 != (count = in.read(buffer))) {content.append(new String(buffer,0,count));}} catch (IOException e) {return null;}return content.toString();} }使用stub替換web資源的測試方法:
import org.junit.*; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; import org.mortbay.jetty.servlet.Context;import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL;import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;/*這種測試的核心思想就是,在我的測試過程中,搭建一個服務器,并在服務器上備上資源,,我測試的方法,將會來訪問我這個服務器,由于服務器中的資源是我自己準備的,所以我可以對獲取的資源的正確性進行判斷。這個測試用到的比價有技術含量的點有:1.內嵌式服務器Jetty,這個我只需要研究一下Jetty配置自己的處理器在正式開始整理之前,先回憶一下Tomcat中server.xml標簽中說的一些關系:host中有許多個contextengine中有許多個hostservice中有多個connector與一個Engineserver中有多個service我注意到一件事情,在使用Jetty時,作者總是先New出一個Server來,在Server中設置端口號8080.這個已經和Tomcat有點不一樣了。其次Tomcat中是在web.xml中配置servlet與url的匹配,但是Jetty中是先New出一個Context,然后將server及相應的url傳入。最后調用setHandler()方法,設置該url的處理類。Tomcat中Context中的概念貌似和Jetty中的Context是類似的。我沒有細究,但是我記得在寫Servlet時,我們總是用到一些Context中的參數。這部分以后再復習一下吧。感覺把這些東西分析完了,自己也就理解了Jetty配置的過程。*/ @Ignore public class TestWebClient {@BeforeClasspublic static void setUp() throws Exception {Server server = new Server(8080);TestWebClient t = new TestWebClient();Context contextOkContext = new Context(server,"/textGetContentOk");contextOkContext.setHandler(t.new TestGetContentOkHandler());Context contextNotFoundContext = new Context(server, "/testGetContentNotFound");contextNotFoundContext.setHandler(t.new TestGetContentNotFoundHandler());server.setStopAtShutdown(true);server.start();}private WebClient client;@Beforepublic void ready(){client = new WebClient();}@Testpublic void testGetContentOk() throws Exception{String result = client.getContent(new URL("http://localhost:8080/textGetContentOk"));assertEquals("It works",result);}@Testpublic void testGetContentNotFound() throws MalformedURLException {String result = client.getContent(new URL("http://localhost:8080/testGetContentNotFound"));assertNull(result);}@AfterClasspublic static void tearDown(){}public class TestGetContentOkHandler extends AbstractHandler {public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException {OutputStream out = httpServletResponse.getOutputStream();/*這個地方的寫法和我以前看到的不一樣哦*/ // ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(); // writer.write("It works"); // writer.flush();/*感覺有必要把HTTP學習一下了*/ // httpServletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH,writer.size()); // writer.writeTo(out); // out.flush();/*我擦嘞,什么鬼,作者花式秀,結果還是錯的,我這簡簡單單的一寫,既然是對的*/out.write("It works".getBytes("iso-8859-1"));out.flush();}}public class TestGetContentNotFoundHandler extends AbstractHandler{public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException {httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);}}}利用替換連接的方法:
import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test;import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.*;import static org.junit.Assert.assertEquals;/*第二個方案:替換連接該方案的核心技術是,利用Java中URL和HttpURLConnection類,我們引入自定義的協議處理器來處理任何類型的通信協議。技術要點:1.為了實現一個自定義的URL協議處理器,你需要調用URL的setURLStreamHandlerFactory方法,并傳遞給它一個自定義的URLStreamHandlerFactory。無論何時調用URL的openConnection方法,都會調用URLStreamHandlerFactory類,返回一個URLStreamHandler對象。(之前在getContent中調用這個方法時,得到的是一個connection對象,現在說是一個URLStreamHandler對象,有點奇怪的哦。)public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac)設置應用程序的 URLStreamHandlerFactory。在一個給定的 Java 虛擬機中,此方法最多只能調用一次。URLStreamHandlerFactory 實例用于從協議名稱構造流協議處理程序。public URLStreamHandler createURLStreamHandler(String protocol)創建具有指定協議的新 URLStreamHandler 實例。*/public class TestWebClient1 {@BeforeClasspublic static void setUP(){TestWebClient1 t = new TestWebClient1();URL.setURLStreamHandlerFactory(t.new StubStreamHandlerFactory());}@Testpublic void testGetContentOk() throws MalformedURLException {WebClient client = new WebClient();String result = client.getContent(new URL("http://loalhost"));assertEquals("It works",result);}private class StubHttpURLConnection extends HttpURLConnection {private boolean isInput = true;public StubHttpURLConnection(URL u) {super(u);}/*你想要的流里,我已經給你放好的東西。*/@Overridepublic InputStream getInputStream() throws IOException {if(!isInput){new ProtocolException("Wrong in isInput...");}ByteArrayInputStream bais = new ByteArrayInputStream("It works".getBytes("ISO-8859-1"));return bais;}public void disconnect() {}public boolean usingProxy() {return false;}public void connect() throws IOException {}}private class StubStreamHandlerFactory implements URLStreamHandlerFactory{public URLStreamHandler createURLStreamHandler(String protocol) {return new StubHttpURLStreamHandler();}}private class StubHttpURLStreamHandler extends URLStreamHandler{protected URLConnection openConnection(URL u) throws IOException {return new StubHttpURLConnection(u);}} }?
《Junit實戰》筆記
轉載于:https://www.cnblogs.com/junjie2019/p/10622797.html
總結
以上是生活随笔為你收集整理的利用stub技术进行单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java-Runoob:Java Str
- 下一篇: A Network-based End-