Reputation: 15158
I apologize if this a duplicate question (I didn't find anything like that). I'm trying to build an OpenId Authentication service and unit test it, currently I have the following setup:
public class OpenIdAuthenticationService : IAuthenticationService
{
private IConfigurationService _configService;
private OpenIdRelyingParty _openIdRelyingParty;
public OpenIdAuthenticationService(IConfigurationService configService)
{
_configService = configService;
_openIdRelyingParty = new OpenIdRelyingParty();
}
}
Apparently OpenIdRelyingParty requires access to HttpContext, is there a way to mock OpenIdRelyingParty and inject it the service ? Or maybe mock HttpContext and provide it to OpenIdRelyingParty somehow ?
Upvotes: 0
Views: 369
Reputation: 81801
OpenIdRelyingParty
can be used in unit tests by using the method overloads that accept an HttpRequestBase
, which is totally mockable. Only the methods that don't take that as a parameter require an HttpContext.Current
.
Upvotes: 1
Reputation: 3040
To mock HttpContext for OpenIdRelyingParty you should modify the code of that class. Even you would waste some time mocking it due that it is a sealed class (but is not impossible you can use MOCKWCF).
I think that is better make a wrapper or adapter for OpenIdRelyingParty. like:
public class OpenIdRelyingPartyWrapped
{
private OpenIdRelyingParty openIdRelyingPartyTarget;
....
public virtual IAuthenticationRequest CreateRequest(string text)
{
return this.openIdRelyingPartyTarget.CreateRequest(text);
}
...
}
Then you will able to mock it as you want.
Upvotes: 1
Reputation: 141668
I would, since you are already doing it, inject OpenIdRelyingParty
into your constructor as you are doing with your configuration service.
Barring that, you could mock the HttpContext in your unit test. HttpContext.Current
has a setter, so set it to a mock/stub HttpContextBase
. Here's an example using NSubstitute with NUnit:
[TearDown]
public void CleanUp()
{
HttpContext.Current = null;
}
[Test]
public void FakeHttpContext()
{
var context = Substitute.For<HttpContextBase>();
var request = Substitute.For<HttpRequestBase>();
context.Request.Returns(request);
//Do any more arragement that you need.
//Act
//Assert
}
This to me would be a bit of a code smell though. It's testing dependencies of dependencies (or however far down that rabbit hole goes). It's useful though when refactoring isn't an option.
Upvotes: 1