Rhino mock noob - 设置存根并分配web响应所需的帮助

时间:2015-07-02 15:21:30

标签: c# asp.net asp.net-mvc mocking rhino-mocks

我对Rhino Mocks完全不熟悉......实际上是嘲笑。我仍然围绕如何编码模拟进行了解决,并且非常感谢一些指导。

我有一个包含类似内容的测试类:

  [Test Class]     

    IGeneralMethods myGeneralMethods = new services.Models.GeneralMethods();
        MockRepository mockEngine = new MockRepository();
        IGeneralMethods simulatedService = mockEngine.DynamicMock<IGeneralMethods>();

        simulatedService.Stub(x => x.GetWebResponse().GetResponseStream() = myFakeResponse);

现在最后一行(不起作用)我正在尝试创建一个存根,这就是我遇到的问题。我想要存根的代码是:

public WebResponse GetWebResponse(WebRequest request)
    {
        try
        {
            WebResponse getResponse = request.GetResponse(); 
            return getResponse;
        }
        catch
        {
            //other actions
        }
        return null;
    }

我还有另一种可以创建WebResponse的方法,所以我想要做的就是停止GetWebResponse方法实际尝试发出请求并返回我的假/预制Web响应。

然而,我不是史酷比从哪里开始的?

更新

我一直在调整代码并取得进展。这是我最新的代码(正在进行的工作):

        MockRepository mockEngine = new MockRepository();

        byte[] responseData = Encoding.UTF8.GetBytes("my XML here");
        Stream stream = new MemoryStream(responseData);
        WebRequest request = (WebRequest)mockEngine.StrictMock(typeof(WebRequest));
        WebResponse response = (WebResponse)mockEngine.StrictMock(typeof(WebResponse));
        Expect.On(request).Call(request.GetResponse()).Return(response);
        Expect.On(response).Call(response.GetResponseStream()).Return(stream);


        var stubbedGetWebResponse = mockEngine.Stub<IGeneralMethods>();

        stubbedGetWebResponse.Stub(x => x.ModeltoXml(newTicket)).Return("test");
        stubbedGetWebResponse.Stub(x => x.GetWebResponse(request)).Return(response);


        var test = new MyApi().NewIn(newTicket, referrer, stubbedGetWebResponse);

        stubbedGetWebResponse.VerifyAllExpectations();

我确定我没有抓到这里的东西,因为当我调试测试时,我的ModeltoXml方法没有返回字符串'test'。我已经删除了这个方法,因为我也注意到在我测试的类中将一个填充的模型传递给它,ModeltoXml方法只返回n​​ull。所以我猜测Rhino已经在我的IGeneralMethods类中删除了所有方法。

1 个答案:

答案 0 :(得分:2)

Since WebRequest is an abstract class, try using a PartialMock. PartialMock will let you override those virtual methods.

// Arrange
var mockResp = MockRepository.GeneratePartialMock<WebResponse>();
var responseData = Encoding.UTF8.GetBytes("my XML here");
var stream = new MemoryStream(responseData);
mockResp.Expect(x => x.GetResponseStream()).Return(stream);

var mockReq = MockRepository.GeneratePartialMock<WebRequest>();
mockReq.Expect(x => x.GetResponse()).Return(mockResp);

// Act
// test here!

// Assert
mockReq.VerifyAllExpectations();
mockResp.VerifyAllExpectations();