简体   繁体   中英

Mocking HttpWebResponse with Rhino Mock

I'm just starting out with mocking and have opted for Rhino Mock. I have a method which includes two methods that I want to mock out.

They are basically calls to methods which will return an HttpWebResponse. As I'm keen to do unit testing I want to drop my dependency to the external site that these methods normally talk to. Instead I want to create a fake response based on my own conditions eg Status codes 200, 404, 500 etc.

I've tried looking around but I've only seen old examples or what seem like very convoluted workarounds to mock an HttpWebResponse. It's for this reason I wanted to post the question in the hope that under the latest Rhino Mock release there is a slicker, shorter and easier solution.

Example of one of the articles I've reviewed: http://javahow.net/questions/9823039/is-it-possible-to-mock-out-a-net-httpwebresponse

I've no worthwhile code to show that would be relevant here. I'm just looking for concise examples where HttpWebResponse has been mocked using the AAA approach as part of a unit test.

Thanks in advance!

I found a code segment available here which seems to do the job. I'm still to put it through it's paces but there's less lines of code etc. I'm using WebRequest on my methods now which I'm looking to test:

https://github.com/ayende/rhino-mocks/blob/master/Rhino.Mocks.Tests/FieldsProblem/FieldProblem_SpookyET.cs

 public void MockHttpRequesteRsponse() 
     { 
         byte[] responseData = Encoding.UTF8.GetBytes("200 OK"); 
         Stream stream = new MemoryStream(responseData); 
         WebRequest request = (WebRequest)mocks.StrictMock(typeof(WebRequest)); 
         WebResponse response = (WebResponse)mocks.StrictMock(typeof(WebResponse)); 
         Expect.On(request).Call(request.GetResponse()).Return(response); 
         Expect.On(response).Call(response.GetResponseStream()).Return(stream); 


         mocks.ReplayAll(); 


         Stream returnedStream = GetResponseStream(request); 


         Assert.Same(stream, returnedStream); 
         string returnedString = new StreamReader(returnedStream).ReadToEnd(); 
         Assert.Equal("200 OK", returnedString); 
     } 

//

private Stream GetResponseStream(WebRequest request) 
     { 
         return request.GetResponse().GetResponseStream(); 
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM