I'm trying to figure out a way to create a MockRepository that implements a repository interface. Currently, this is what I have:
public class MockUserRepository
{
private readonly IList<User> _users;
public MockUserRepository()
{
_users = new List<User>()
{
new User()
{
UserId = new Guid("E480E40F-6802-4296-B2A8-E0D5E018CD41"),
Username = "admin",
Password = "5A105E8B9D40E1329780D62EA2265D8A",
CellPhone = "3175172957"
}
};
}
public IUserRepository Create()
{
var mockUserRepository = new Mock<IUserRepository>();
mockUserRepository.Setup(m => m.Count()).Returns(_users.Count());
mockUserRepository.Setup(m => m.Get()).Returns(_users);
mockUserRepository.Setup(m => m.Get(It.IsAny<Guid>())).Returns((Guid id) => _users.First(x => x.UserId == id));
mockUserRepository.Setup(m => m.Save(It.IsAny<User>())).Returns(
(User user) =>
{
var now = DateTime.Now;
user.ModifiedOn = now;
if(user.UserId.Equals(Guid.Empty))
{
user.CreatedOn = now;
_users.Add(user);
}
else
{
var original = _users.First(x => x.UserId == user.UserId);
if (original == null)
{
return false;
}
original = user;
}
return true;
}
);
mockUserRepository.Setup(m => m.Find(It.IsAny<IList<object[]>>())).Returns(
(IList<object[]> criteria) =>
{
IList<User> uList = _users.ToList();
foreach (object[] criteriaItem in criteria)
{
var name = (string)criteriaItem[0];
var value = (string)criteriaItem[1];
IList<User> tempList = uList.ToList();
IList<User> addList = tempList.Where(user => (string) user.GetType().GetProperty(name).GetValue(user, null) == value).ToList();
uList = addList;
}
return uList;
});
return mockUserRepository.Object;
}
}
I would like to have something like this:
public class MockUserRepository : IUserRepository
Then, just have all of my mocked methods actually implemented. I want to do this to enforce my developers to fully mock out a repository based on the interface.
From the test side, this Mocked Repository is used like this:
[SetUp]
public void Setup()
{
MockUserRepository = new MockUserRepository().Create();
MockRoleRepository = new MockRoleRepository().Create();
MockQuestionRepository = new MockQuestionRepository().Create();
AuthenticationService = new AuthenticationService(MockUserRepository, MockRoleRepository, MockQuestionRepository);
}
All of this works just fine, but I'm really stuck on enforcing my MockRepository to implement all of its interface's methods.
this is over-complicating the use of mocks. simply Mock the IUserRepository interface in the test and then mock the methods you need based on the tests.
reposistory = new Mock<IUserRepository>();
var id = 1;
var user = new User();
repository.Setup(x=> x.Get(id)).Returns(user);
var sut = new Service(repository.Object);
var result = sut.Get(id);
Assert.Equals(user, result);
If you really want a "blank" object just implement a Fake IUserRepository and forgo a mocking framework altogether.
class FakeUserRepository : IUserRepository
{
public List<User> Users = new List<Users>();
public User Get(long id)
{
return Users.FristOrDetail(x=>x.Id = id);
}
}
var id = 1;
var user = new User();
var repository = new FakeUserRepository();
repository.Users.Add(user);
var sut = new Service(repository);
var result = sut.Get(id);
Assert.Equals(user, result);
Related
i'm new to unit testing and Moq. I wrote 4 tests who all throw the same exception and i think i need to add these parameters CombatHelperContext, IMapper when mocking the CharacterRepository but how do i do that?
My goal is to test crud functionality, views and more.
public class CharacterTests
{
[Fact]
public async Task GetAll_ReturnsAViewResult_WithAListOfCharacters()
{
// Arrange
var mockRepo = new Mock<CharacterRepository>();
mockRepo.Setup(repo => repo.GetAll())
.Returns(GetTestCharacters());
var controller = new CharacterController(mockRepo.Object);
// Act
var result = await controller.Get();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<List<CharacterDto>>(
viewResult.ViewData.Model);
Assert.Equal(4, model.Count());
}
[Fact]
public async Task Delete_Character()
{
// Arrange
var mockRepo = new Mock<CharacterRepository>();
mockRepo.Setup(repo => repo.Delete(1));
var controller = new CharacterController(mockRepo.Object);
var characters = GetTestCharacters();
// Act
var result = await controller.Get();
// Assert
Assert.Null(characters.Where(c => c.Id == 1));
}
[Fact]
public async Task Post_NewCharacter_ReturnsInViewResult()
{
// Arrange
CharacterDto newCharacterDto = new CharacterDto();
newCharacterDto.Id = 5;
var mockRepo = new Mock<CharacterRepository>();
mockRepo.Setup(repo => repo.Add(newCharacterDto));
var controller = new CharacterController(mockRepo.Object);
var characters = GetTestCharacters();
// Act
var result = await controller.Get();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<List<CharacterDto>>(
viewResult.ViewData.Model);
Assert.Equal(5, model.Count());
}
[Fact]
public async Task Update_Character()
{
// Arrange
var mockRepo = new Mock<CharacterRepository>();
var characters = GetTestCharacters();
CharacterDto characterToUpdate = characters.FirstOrDefault(c => c.Name == "Zero Two");
var controller = new CharacterController(mockRepo.Object);
// Act
var result = await controller.Get();
characterToUpdate.Name = "Zero Three";
mockRepo.Setup(repo => repo.Update(characterToUpdate));
// Assert
Assert.NotNull(characters.FirstOrDefault(c => c.Name == "Zero Three"));
}
private IQueryable<CharacterDto> GetTestCharacters()
{
var characters = new List<CharacterDto>();
characters.Add(new CharacterDto()
{
Id = 1,
Name = "Zero Two"
});
characters.Add(
new CharacterDto
{
Id = 2,
Name = "Ander"
});
characters.Add(
new CharacterDto
{
Id = 3,
Name = "Jingles"
});
characters.Add(new CharacterDto
{
Id = 4,
Name = "Arthas Menethil"
});
var queryableCharacters = characters.AsQueryable();
return queryableCharacters;
}
}
This the Repository i'm mocking
public class CharacterRepository : MappingRepository<Character, CharacterDto>
{
public CharacterRepository(CombatHelperContext combatHelperContext, IMapper mapper) : base(combatHelperContext, mapper)
{
}
}
Depend on abstraction rather than implementation - create repository interface:
public interface ICharacterRepository
{
IEnumerable<Character> GetAll();
void Delete(int id);
void Add(Character character);
}
Now mocking works like a charm:
var mockRepo = new Mock<ICharacterRepository>();
Also consider using something like AutoFixture or NBuilder to generate test objects.
[Fact]
public async Task GetAll_Returns_ViewResult_With_List_Of_Characters()
{
// Arrange
var fixture = new Fixture();
var characters = fixture.CreateMany<Character>();
var mockRepo = new Mock<ICharacterRepository>();
mockRepo.Setup(repo => repo.GetAll()).Returns(characters);
var controller = new CharacterController(mockRepo.Object);
// Act
var result = await controller.Get();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<List<CharacterDto>>(viewResult.ViewData.Model);
Assert.Equal(characters.Count(), model.Count());
}
If you cannot change current implementation and depend on interface, then you should provide constructor arguments as params list to new mock:
var combatHelperContext = new CombatHelperContext();
var mapperMock = new Mock<IMapper>();
var mockRepo = new Mock<CharacterRepository>(combatHelperContext, mapperMock.Object);
I am writing unit tests and this mapper is causing me grief again. I understood from a previous post that I cannot Mock the mapper, i have to use it straight away. So I have created maps but it says missing type map configuration.
public RoleDto GetSingle([FromRoute] string id)
{
var r = roleManagerWrapper.GetSingleRole(id);
return mapper.Map<RoleDto>(r);
}
It breaks when it tries to map the object. Is there any special mapping for Task <IdentityRole> that needs to be implemented?
public async Task<IdentityRole> GetSingleRole(string roleId)
{
var role = await this.roleManager.Roles.SingleOrDefaultAsync(r => r.Id == roleId);
return role;
}
Here is my test that only counts the number of roles that are created.
[Test]
public async Task Get_Single()
{
TestSetup();
var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();
var adminRole = new IdentityRole()
{
Name = "Admin",
Id = "4a8de423-5663-4831-ac07-7ce92465b008"
};
var managerRole = new IdentityRole()
{
Name = "Manager",
Id = "40f74162-3359-4253-9b5a-ad795b328267"
};
ApplicationDbContext.Roles.Add(managerRole);
ApplicationDbContext.Roles.Add(adminRole);
ApplicationDbContext.SaveChanges();
var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, Mapper);
var result = sut.GetSingle("4a8de423-5663-4831-ac07-7ce92465b008");
Assert.AreEqual(result.UserCount, 1);
}
protected void TestSetup(string databaseName = null)
{
if (databaseName == null)
{
databaseName = GetTestName();
}
TestCleanup();
ServiceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
dbContextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName)
.UseInternalServiceProvider(ServiceProvider)
.Options;
ApplicationDbContext = new ApplicationDbContext(dbContextOptions);
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RoleDto, IdentityRole>();
cfg.CreateMap<IdentityRole, RoleDto>();
cfg.CreateMap<CreateRoleDto, IdentityRole>().ReverseMap();
cfg.CreateMap<UpdateRoleDto, IdentityRole>().ReverseMap();
});
Mapper = config.CreateMapper();
}
The action needs to be refactored to use proper asyn syntax since GetSingleRole returns Task<IdentityRole>
public Task<RoleDto> GetSingle([FromRoute] string id) {
IdentityRole r = await roleManagerWrapper.GetSingleRole(id);
return mapper.Map<RoleDto>(r);
}
And the test updated accordingly
[Test]
public async Task Get_Single() {
//Arrange
TestSetup();
var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();
//...omitted for brevity
var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, Mapper);
//Act
RoleDto result = await sut.GetSingle("4a8de423-5663-4831-ac07-7ce92465b008");
//Assert
Assert.AreEqual(result.UserCount, 1);
}
I have ChangePassword method where I have User.Identity.GetUserId() to find UserId.
Problem: It always return null. Don't understand why.
I read in another post that the GetUserById use below line of code to find Id. I am not sure how do I mock ClaimsTypes.NameIdentifier.
return ci.FindFirstValue(ClaimTypes.NameIdentifier);
ChangePassword method (method to be unit testes)
public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword)
{
_tstService = new TestService();
IdentityResult result = await _tstService.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
Unit Test
var mock = new Mock<MyController>();
mock.CallBase = true;
var obj = mock.Object;
obj.ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() };
obj.Request.SetOwinContext(CommonCodeHelper.mockOwinContext());
IPrincipal user = GetPrincipal();
obj.ControllerContext.RequestContext.Principal = user;
var result = await obj.ChangePassword(dto);
//GetPrincipal
public static IPrincipal GetPrincipal()
{
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
identity.Setup(x => x.Name).Returns("User1#Test.com");
identity.Setup(p => p.IsAuthenticated).Returns(true);
user.Setup(x => x.Identity).Returns(identity.Object);
Thread.CurrentPrincipal = user.Object;
return user.Object;
}
IOwinContext mocking code
public static IOwinContext mockOwinContext()
{
var owinMock = new Mock<IOwinContext>();
owinMock.Setup(o => o.Authentication.User).Returns(new ClaimsPrincipal());
owinMock.Setup(o => o.Request).Returns(new Mock<OwinRequest>().Object);
owinMock.Setup(o => o.Response).Returns(new Mock<OwinResponse>().Object);
owinMock.Setup(o => o.Environment).Returns(new Dictionary<string, object> { { "key1", 123 } });
var traceMock = new Mock<TextWriter>();
owinMock.Setup(o => o.TraceOutput).Returns(traceMock.Object);
var userStoreMock = new Mock<IUserStore<IfsUser>>();
userStoreMock.Setup(s => s.FindByIdAsync("User1#ifstoolsuite.com")).ReturnsAsync(new IfsUser
{
Id = "User1#test.com",
FirstName = "Test",
LastName = "User1",
Email = "User1#test.com",
UserName = "User1#test.com",
});
var applicationUserManager = new IfsUserManager(userStoreMock.Object);
owinMock.Setup(o => o.Get<IfsUserManager>(It.IsAny<string>())).Returns(applicationUserManager);
return owinMock.Object;
}
Your GetPrincipal can be updated to use claims.
public static IPrincipal GetPrincipal() {
//use an actual identity fake
var username = "User1#Test.com";
var identity = new GenericIdentity(username, "");
//create claim and add it to indentity
var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
identity.AddClaim(nameIdentifierClaim);
var user = new Mock<IPrincipal>();
user.Setup(x => x.Identity).Returns(identity);
Thread.CurrentPrincipal = user.Object;
return user.Object;
}
Here is an example that shows how the above approach works.
public partial class MiscUnitTests {
[TestClass]
public class IdentityTests : MiscUnitTests {
Mock<IPrincipal> mockPrincipal;
string username = "test#test.com";
[TestInitialize]
public override void Init() {
//Arrange
var identity = new GenericIdentity(username, "");
var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
identity.AddClaim(nameIdentifierClaim);
mockPrincipal = new Mock<IPrincipal>();
mockPrincipal.Setup(x => x.Identity).Returns(identity);
mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);
}
[TestMethod]
public void Should_GetUserId_From_Identity() {
var principal = mockPrincipal.Object;
//Act
var result = principal.Identity.GetUserId();
//Asserts
Assert.AreEqual(username, result);
}
[TestMethod]
public void Identity_Should_Be_Authenticated() {
var principal = mockPrincipal.Object;
//Asserts
Assert.IsTrue(principal.Identity.IsAuthenticated);
}
}
}
You have some design issues. Creating a concrete TestService will cause problems if it as connecting to an actual implementation. That becomes an integration test. Abstract that dependency as well.
public interface ITestService {
Task<IdentityResult> ChangePassword(string userId, string oldPassword, string newPassword);
}
public abstract class MyController : ApiController {
private ITestService service;
protected MyController(ITestService service) {
this.service = service;
}
public async Task<IHttpActionResult> ChangePassword(string NewPassword, string OldPassword) {
IdentityResult result = await service.ChangePassword(User.Identity.GetUserId(), OldPassword, NewPassword);
if (!result.Succeeded) {
return GetErrorResult(result);
}
return Ok();
}
}
Also you should not mock the System under test. You should mock the dependencies of the SUT. Based on your method to be tested and what you indicated in the comments that MyController is an abstract class, the following test should apply
[TestClass]
public class MyControllerTests {
public class FakeController : MyController {
public FakeController(ITestService service) : base(service) { }
}
[TestMethod]
public void TestMyController() {
//Arrange
var mockService = new Mock<ITestService>();
mockService
.Setup(m => m.ChangePassword(....))
.ReturnsAsync(....);
var controller = new FakeController(mockService.Object);
//Set a fake request. If your controller creates responses you will need this
controller.Request = new HttpRequestMessage {
RequestUri = new Uri("http://localhost/api/my")
};
controller.Configuration = new HttpConfiguration();
controller.User = GetPrincipal();
//Act
var result = await controller.ChangePassword("NewPassword", "OldPassword");
//Assert
//...
}
}
I'm using Moq for the first time, and I'm struggling with getting the tests to run properly.
I'm trying to moq the Save() method of my service layer.
public void Save(UserViewModel viewModel)
{
// todo: this still doesn't address updating a password. The UserViewModel doesn't contain any Password data.
if (viewModel.Id != Guid.Empty)
{
// The UserId is not empty, we're either updating an existing user
// or we're inserting a new user via sync
var user = _userRepository.GetById(viewModel.Id);
if (user != null)
{
// Looks like we're updating a user because they're already in the database.
_userRepository.Update(_userViewModelToModelMapper.BuildFrom(viewModel));
return;
}
}
// The user is being created, either via a Sync (Guid Exists), or via an Insert (Guid doesn't Exist)
_userRepository.Create(_userViewModelToModelMapper.BuildFrom(viewModel));
}
I've got Three tests, of which, I'm not sure any of them are right. The first two are passing, but the third one fails with
Moq.MockVerificationException : The following setups were not matched:
IUserRepository r => r.Update(It.Is(um => um.Equals()))
Here are the tests.
// PASSES but could be suspect
[Test]
public void ShouldSaveANewUserFromExistingId()
{
// emulating a "sync"
// Setup
var userId = new Guid("81C7FE19-2DB5-4083-BD6A-5433687561F7");
var userModel = new UserModel();
var userViewModel = new UserViewModel {Id = userId};
var userRepository = new Mock<IUserRepository>();
var viewModelToModelMapper = new Mock<IAutoMapper<UserViewModel, UserModel>>();
var modelToViewModelMapper = new Mock<IAutoMapper<UserModel, UserViewModel>>();
// Setup the Mock UserRepository
userRepository.Setup(r => r.Create(It.Is<UserModel>(um => um.Equals(userModel))));
viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<UserViewModel>(u => u.Equals(userViewModel))))
.Returns(userModel);
var userService = new UserService(userRepository.Object, viewModelToModelMapper.Object, modelToViewModelMapper.Object);
// Execute
userService.Save(userViewModel);
// Assert
userRepository.VerifyAll();
viewModelToModelMapper.VerifyAll();
}
// PASSES but could be suspect.
[Test]
public void ShouldSaveANewUser()
{
// emulating a standard create
// Setup
var userId = Guid.Empty;
var userModel = new UserModel();
var userViewModel = new UserViewModel { Id = userId };
var userRepository = new Mock<IUserRepository>();
var viewModelToModelMapper = new Mock<IAutoMapper<UserViewModel, UserModel>>();
var modelToViewModelMapper = new Mock<IAutoMapper<UserModel, UserViewModel>>();
// Setup the Mock UserRepository
userRepository.Setup(r => r.Create(It.Is<UserModel>(um => um.Equals(userModel))));
viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<UserViewModel>(u => u.Equals(userViewModel))))
.Returns(userModel);
var userService = new UserService(userRepository.Object, viewModelToModelMapper.Object, modelToViewModelMapper.Object);
// Execute
userService.Save(userViewModel);
// Assert
userRepository.VerifyAll();
viewModelToModelMapper.VerifyAll();
}
// FAILS MISERABLY
[Test]
public void ShouldSaveAnExistingUser()
{
// emulating an "Update"
// Setup
var userId = new Guid("0A88AEC2-9F8D-44DE-BD01-3EB9A23C78E3");
var userModel = new UserModel { Id = userId };
var userViewModel = new UserViewModel { Id = userId };
var userRepository = new Mock<IUserRepository>();
var viewModelToModelMapper = new Mock<IAutoMapper<UserViewModel, UserModel>>();
var modelToViewModelMapper = new Mock<IAutoMapper<UserModel, UserViewModel>>();
// Setup the Mock UserRepository
userRepository.Setup(r => r.Update(It.Is<UserModel>(um => um.Equals(userModel))));
viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<UserViewModel>(u => u.Equals(userViewModel))))
.Returns(userModel);
var userService = new UserService(userRepository.Object, viewModelToModelMapper.Object, modelToViewModelMapper.Object);
// Execute
userService.Save(userViewModel);
// Assert
userRepository.VerifyAll();
viewModelToModelMapper.VerifyAll();
}
Where am I going wrong with my Moqing?
Seems like in the last case you would need:
userRepository.Setup(r => r.GetById(userId)).Returns(userModel);
Before the userService.Save call. Without it userRepository.GetById will always be null and the update branch will never be taken.
In my apicontroller I use base.user to identify the authenticated user to use in a lookup. Now I am writing a unit test for this but I cannot figure out how to mock apicontroller.user. Do I need to create a request and set the user there? Or is there another way to set the controller.user?
Here is my controller; I have already mocked repository and membershipservice.
[Authorize]
public class DocumentController : ApiController
{
DocumentRepository _repository;
IStaticMembershipService _membership;
public IEnumerable<Document> GetDocuments()
{
MembershipUser userAccount = _membership.GetUser(base.User);
IEnumerable<Document> docs = null;
if (userAccount != null)
{
docs = _repository.GetDocumentsByUserId(
(Guid) userAccount.ProviderUserKey);
}
return docs;
}
Here is my unit test:
[TestClass]
public class DocumentControllerWebService
{
private DocumentsContext _context;
private DocumentRepository _repository;
private DocumentController _controller;
private FakeMembershipService _membership;
private TestContext testContextInstance;
[TestInitialize]
public void MyTestInitialize()
{
// Create a context with a fake data set provider
_context = new DocumentsContext(new FakeDbSetProvider());
_repository = new DocumentRepository(_context);
_membership = new FakeMembershipService();
_controller = new DocumentController(_repository, _membership);
}
public void GetDocumentsTest()
{
string userName = "someUser";
MembershipUser userAccount = _membership.GetUser(userName);
Guid userId = (Guid) userAccount.ProviderUserKey;
Guid anotherUserId = Guid.NewGuid();
// Get some dummy data and insert it into the fake repository
List<Document> forms = DocumentDummyData.GetListOfDummyData(
userId, anotherUserId);
forms.ForEach(f => _repository.InsertDocument(f));
// I would like to do this but User is readonly
_controller.User = userName;
List<Document> docs = _controller.GetDocuments().ToList();
foreach (Document expected in forms.Where(d => d.UserId == userId))
{
Document actual = docs.Where(
d => d.DocumentID == expected.DocumentID).FirstOrDefault();
Assert.IsNotNull(actual);
Assert.AreEqual(expected.DocumentID, actual.DocumentID);
}
}
}
If you are getting the user from http Request then you'll want to look at a way of mocking that out. Thankfully that has been done many times. A good place to start would be to read this
http://www.codethinked.com/post/2008/12/04/Using-SystemWebAbstractions-in-Your-WebForms-Apps.aspx
To summarize what I did which followed this, a hanselman blog and some trial and error:
In your ApiController add this to your constructor
HttpContextWrapper = HttpContextFactory.GetHttpContext();
The factory is this
public static class HttpContextFactory
{
[ThreadStatic]
private static HttpContextBase _mockHttpContext;
public static void SetHttpContext(HttpContextBase httpContextBase)
{
_mockHttpContext = httpContextBase;
}
public static HttpContextBase GetHttpContext()
{
if (_mockHttpContext != null)
{
return _mockHttpContext;
}
if (HttpContext.Current != null)
{
return new HttpContextWrapper(HttpContext.Current);
}
return null;
}
}
Now you have a seam into which you can insert your mock request, response, session, etc.
HttpContextBase httpContext = HttpMocks.HttpContext();
HttpContextFactory.SetHttpContext(httpContext);
Finally here is a fairly fully mocked context that I use
public class HttpMocks
{
public static HttpContextBase HttpContext()
{
var context = MockRepository.GenerateMock<HttpContextBase>();
context.Stub(r => r.Request).Return(HttpRequest());
context.Stub(r => r.Response).Return(HttpResponse());
context.Stub(r => r.Session).Return(HttpSession());
context.Stub(r => r.Server).Return(HttpServer());
return context;
}
private static HttpServerUtilityBase HttpServer()
{
var httpServer = MockRepository.GenerateMock<HttpServerUtilityBase>();
httpServer.Stub(r => r.MapPath("")).IgnoreArguments().Return("");
return httpServer;
}
private static HttpResponseBase HttpResponse()
{
var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();
var cookies = new HttpCookieCollection {new HttpCookie("UserContext")};
httpResponse.Stub(r => r.Cookies).Return(cookies);
Func<string, string> returnWhatWasPassed = x => x;
httpResponse.Stub(r => r.ApplyAppPathModifier(""))
.IgnoreArguments().Do(returnWhatWasPassed);
return httpResponse;
}
public static HttpRequestBase HttpRequest()
{
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
var cookies = new HttpCookieCollection
{
new HttpCookie("UserContext")
};
httpRequest.Stub(r => r.Cookies).Return(cookies);
var parameters = new NameValueCollection
{
{ "id", "277" },
{ "binderId", "277" }
};
httpRequest.Stub(r => r.Params).Return(parameters);
httpRequest.Stub(r => r.ApplicationPath).Return("/");
httpRequest.Stub(r => r.AppRelativeCurrentExecutionFilePath)
.Return("~/");
httpRequest.Stub(r => r.PathInfo).Return("");
var serverVariables = new NameValueCollection();
httpRequest.Stub(r => r.ServerVariables).Return(serverVariables);
return httpRequest;
}
public static HttpSessionStateBase HttpSession()
{
var s = new FakeSessionState();
s["mocking"] = "true";
return s;
}
}
this makes for a rather long answer but let us know if you need more detail on anything, you can probably ignore fake session for now.