The method under test is simple enough
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void SetCookie(IHttpContextService context) | |
{ | |
if (context == null) | |
return; | |
if (context.User == null) | |
return; | |
if (context.User.Identity == null) | |
return; | |
if (!context.User.Identity.IsAuthenticated) | |
return; | |
this.UserName = context.User.Identity.Name; | |
// Create a cookie for username and key | |
var cookie = new HttpCookie("Token", this.UserNameOnly + "|" + GetKey(this.Input)); | |
context.CookieCollection.Add(cookie); | |
} |
as is the test case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Test] | |
public void Should_SetACookie() | |
{ | |
var httpContextService = MockRepository.GenerateStub<IHttpContextService>(); | |
var cookieCollection = new HttpCookieCollection(); | |
IPrincipal user = new GenericPrincipal(new GenericIdentity("Test"), | |
new[] {"TestRole"}); | |
httpContextService.Stub(c => c.User).Return(user); | |
httpContextService.Stub(c => c.CookieCollection).Return(cookieCollection); | |
cookieSetter.SetCookie(httpContextService); | |
httpContextService.VerifyAllExpectations(); | |
} |
The mocking Framework is Rhino Mocks and this was the solution to the problem.
With Rhino a call to a stub (or mock) is expected only once while my method is checking the user object a number of times. Eventually the test will just check that the cookie has been set so I can change the User stub to:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
httpContextService.Stub(c => c.User).Return(user).Repeat.Any(); |
No comments:
Post a Comment