Easily mockable HTTP client framework for C# - c#

In a upcoming project I'm going to write an application in C# which partly has to communicate with a HTTP server. I'm very fond of writing my code TDD-style, and I would just love it if I could mock all of the HTTP requests in my tests.
Does any one here know about an easly mockable HTTP client framework?
Ps. I usually use Moq for mocks. If you know of some free mocking framework that would be better to mock HTTP requests, that would be nice too.

DotNetOpenId, an open source project from which you may reuse code, uses HTTP wrapper classes through which all calls are made. During testing, a mock HTTP handler is injected so that the responses can be programmatically set before the call is made. It has another mode where it hosts its own ASP.NET site so that the full actual stack can be exercised.
This works well, although it hasn't been pulled out as a standalone solution. If you're interested in reusing it, here are some relevant links to the source. And you can ask for help integrating it at dotnetopenid#googlegroups.com.
Live one:
StandardWebRequestHandler.cs
Mocks: MockHttpRequest.cs, TestWebRequestHandler.cs

I suggest you use the framework support for this i.e. System.Net.WebRequest.
Define a really simple interface, and a simple wrapper for the webrequest. This way you will get what you want, and won't add an external dependency for something the framework already does well.

You could use WireMock.Net which is a flexible library for stubbing and mocking web HTTP responses using requests matching criteria.
And this can also be used very easily in unit -test projects. Check the wiki for details.
NuGet is found here.

I don't think there is actually any framework which handles the things you want to archive. After all only you know what each Http request should do. So basically you have 2 options:
Making the calls and using a dummy implementation on the other side. This may be a simple console application which returns dummy data. If you need more logic I would consider using an object database - in my opinion they fit perfectly for these applications.
Use a mock- implementation on the application side. If this implementation has much logic don't use any mocking framework - create a custom mock class which has all the logic.
Hope this helps

Related

Unit testing http requests to rest api

I have a C# library that gets data from public api.
trying to get into TDD and was wondering how to unit test a library that the main focus of it is to get data from the server and convert the json to .net objects. (Basically handling the http requests along with limiting and error handling and some configuration settings)
I know you should mock some sort of database but not sure how exactly. And i've read that the tests should run all the time even with internet connection off.
You can implement only integration testing. You also can test your code with internet connection off - just create a kind of wrapper. Among various design patterns the most appropriate is Facade for this kind of task. Create Facade around third-party library so you can mock this facade in future and make it produce desired/undesired results so you can unit test your classes. But:
Don't test or mock what you don't own

Can an ASP.NET MVC project with attribute routing be tested?

I've spent days trying to mock, stub and fake my way to a testable application. I usually don't test controller actions, but test all my other classes and patterns instead.
The wall I hit was with the new attribute routing feature. While I can use the routing classes to register my rules etc. I get this error when MapMvcAttributeRoutes is called.
This method cannot be called during the application's pre-start initialization phase
This is discussed here.
MapMvcAttributeRoutes: This method cannot be called during the application's pre-start initialization phase
To be honest, I can't understand the answer(s). Not the code, but its fragmented into versions, links to other bugs, GitHub etc.
I'm a bit lost as to the bottom line answer:
As of 23rd October, 2014. Is it possible to register all routes under test conditions, what version of MVC do I need and which classes/methods do I call to do it?
At present, my classes using UrlHelper are screwing up because needed routes are missing. I am injecting subclasses to bypass the issue, but I don't think its unreasonable to fake the runtime MVC environment and have my app run without lots of DI acrobatics.
It would be nice if these was a simple helper in the framework itself that could take a JSON object describing a raw HTTP request and have the Controller, HttpContext, ControllerContext etc. etc. all created properly as if it were a real request off the wire.
Thanks,
Luke
Good question, and I think that the answer is that little or no thought was given to testing routes in the design of this part of the framework. There may be ways to test routes, but they will be indirect, undocumented and prone to break when a new version of MVC ships.
I have a blog post here on my experiences on the topic. I also suggest that you also campaign for better testability in ASP vNext in the public issue tracker.
During a daily stand-up, a colleague mentioned he was integration testing via an in-memory web server. Intrigued, he showed me how and I was amazed, learnt something :-)
You can new-up an HttpServer instance and have it read your config and then invoke the server instance. I have not tried it, but I see no reason why this wouldn't enumerate your routes and code needing proper config will all work.
This SO question is related and may help in how to set this up:
How does the In-Memory HttpServer know which WebAPI project to host?

Creating testable WCF service without OperationContext

I've implemented a subscribe/publish (for my own enjoyment) WCF service which works reasonably well. Like all blogs and books I've seen they all use OperationContext to get the clients callback address. After a bit of reading, due to many people saying not to use OperationContext, I found myself not being able to create proper unit tests. Yet I haven't been able to find an alternative. I suppose the subscribe method could accept a parameter for it to provide its own address? I could see the code being testable from an intergration test stand point of view but not for unit testing since OperationContext would always be null.
How do I get the clients endpoint when they subscribe to my service without using OperationContext?
Little bit of an aside but where is a good WCF resource with testing in mind when showing code samples? There are tons of blogs out there reiterating the same code without providing sample test cases.
Thank you.
Microsoft developers really like sealed and static keywords (as well as internal) and they hate virtual. Because of that standard testing approaches and framworks often don't work. You have two choices:
Wrap access to OperationContext in custom class and inject an instance of the class to your service. This will involve additional work because you will need to do injection somewhere outside your service. For example constructor injection will need custom IInstanceProvider.
Use more poweful testing framework. Check Moles framework which is able to intercept calls and redirect them. This enables "mocking" sealed classes and static methods/properties.
Another approach is simply refactoring your code. Take away all business logic from your service into separate testable business class and let the service participate only in integration test. Service is more like infrastructure and not everything really needs unit test. Integration / end-to-end / behavior test is also test and valid approach.

What's the best way to mock a .net service reference, like Amazon's web services

I've generated some service references to Amazon, and I was wondering if there was a good, quick way to generate mocks against the whole thing, or I instead I have to implement a mock binding, and do it that way
You cannot easily mock a .NET service reference client class. You could use the service contract interface in your code and mock this one.
You might want to have a look at the MockingBird framework.
Disclaimer: I havn't used it myself so I don't know if it serves your need.

Unit testing code that uses PortalSiteMapProvider

I have a web part that uses PortalSiteMapProvider to query the Sharepoint navigation hierarchy, but unit tests written for that code fail, because the code is being run outside the Sharepoint context and thus no site map providers are available.
I've identified two alternate ways of solving this dilemma:
Because Sharepoint is basically an elaborate ASP.Net application, it should be possible to run tests inside the Sharepoint context with the HostType and UrlToTest test attributes
Use a mock instead of PortalSiteMapProvider
Are either of these viable or is there a better third option?
The Microsoft Patterns and Practices dudes recommend TypeMock to help unit test Sharepoint
http://msdn.microsoft.com/en-us/library/dd203468.aspx
http://www.typemock.com/sharepointpage.php
Not a free solution unfortunately.
You will not be able to mock the SPRequest class, which is an internal class. I am facing the same issues.
One approach is to try to isolate your code from the SharePoint API, and this is not so nice.
BTW Typemock have a reduced price product especially for SharePoint.
Second option is more appropriate. Abstract away PSMP and hide it behind IPortalSiteMapProvider and then mock it in your unit test. In order to bridge the interface and concrete implementation you can either write a thin delegating adapter or use duck typing.

Categories

Resources