开发者

Unit Testing legacy code - what to refactor to fit Rhino Mocks contexts?

开发者 https://www.devze.com 2023-01-31 15:39 出处:网络
I\'m trying to retroactively fit some legacy code with unit tests. Not being terribly experienced with unit tests, this is not making me happy :)

I'm trying to retroactively fit some legacy code with unit tests. Not being terribly experienced with unit tests, this is not making me happy :)

The code in question is an MVC controller. I re-factored it to remove direct dependencies and replaced them with interfaces which was all nice and straight forward. However I'm having real trouble getting all the context mocks correct in order to do the testing.

A lot of the code makes calls to both Request.QueryString and Request.Params. I'm not entirely sure why it treats the two separately, but I'm loathe to fiddle with anything I don't actually need to change.

So I put this together to initialise a mocked context:

        var controller = new TestController();

        var request = MockRepository.GenerateMock<HttpRequestBase>();
        var context = MockRepository.GenerateMock<HttpContextBase>();

        var collection = new System.Collections.Specialized.NameValueCollection();   
        collection.Add("Id", "1");   

        context.Expect( c => c.Request ).Return( request ).Repeat.Any();
        request.Expect( r => r.Params ).Return( collection ).Repeat.开发者_StackOverflowAny();
        request.Expect( x => x.QueryString["foo"] ).Return("bar").Repeat.Any();

        controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);

"TestController" is just a local class that inherits from the controller that's being tested. The above code compiles quite happily but when I try and run it I get the following error:

 Previous method 'HttpRequestBase.get_QueryString();' requires a return value or an exception to throw.

Googling this doesn't seem to be terribly helpful.

Question is, what do I refactor here: my test in order to try and get it to build, or my base code so that it just uses Params or QueryString but not both?

Cheers, Matt


This doesn't answer your question directly, but I think that you should try using MVC Contrib's TestControllerBuilder for this kind of testing. It deals with a lot of the dependencies of a controller and lets you concentrate on the bits you need to test.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号