I have seen the following questions already:
These do not help me because I need:
- To test existing code which uses
WebRequest
/WebResponse
directly, with no interfaces - The existing code depends on
HttpWebRequest
/HttpWebResponse
, so I can't use my own derivedWebRequest
andWebResponse
classes.
I know about WebRequest.RegisterPrefix
, and have a successful unit test which proves that it works (once you get the prefix right). But that test simply tests WebRequest
and WebResponse
.
I tried the following, but it gives a compile error (not a warning):
public class MockWebRequest : HttpWebRequest
{
public MockWebRequest()
// : base(new SerializationInfo(typeof (HttpWebRequest), new FormatterConverter()),
// new StreamingContext())
{
}
}
With the two lines commented-out, I get a compile error:
error CS0619: 'System.Net.HttpWebRequest.HttpWebRequest()' is obsolete: 'This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.'
When I uncomment those lines, I get a 618 warning, but the code crashes at runtime:
System.Runtime.Serialization.SerializationException: Member '_HttpRequestHeaders' was not found.
at System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType)
at System.Runtime.Serialization.SerializationInfo.GetValue(String name, Type type)
at System.Net.HttpWebRequest..ctor(SerializationInfo serializationInfo, StreamingContext streamingContext)
at UnitTests.MockWebRequest..ctor(String responseJson)
at UnitTests.MockWebRequestCreator.Create(Uri uri)
at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
at System.Net.WebRequest.Create(Uri requestUri)
at code under test
I'm at a loss about how to proceed with this (other than the default, which is to just punt on these unit tests and wish the code had been implemented with testing in mind).
I could probably get "down and dirty" and do something nasty with ISerializable
, or something like that, but this brings up the third requirement:
3.
The code must be maintainable, and must not be too much more complex than the code being tested!
OBTW, I can't use TypeMock for this, and in fact there's a bit of a time limit. The project is almost done, so a new, purchased mocking framework is out of the question.