Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public ActionResult Index()
- {
- IEnumerable<Colour> colours = null;
- if (isUserAdmin())
- {
- colours = db.Colours;
- }
- else
- {
- string userId = User.Identity.GetUserId();
- IEnumerable<string> userRoleIds = db.Users.Find(userId).Roles.Select(x => x.Id);
- colours = db.ColourRoles.Where(x => userRoleIds.Contains(x.RoleId)).Select(y => y.Colour).Distinct();
- }
- ViewData["Colours"] = colours;
- return View();
- }
- [TestClass]
- public class ControllerUnitTest {
- [TestMethod]
- public void ControllerIndexTest() {
- // Arrange
- var username = "[Test_Username_Here]";
- string[] roles = new[] { "FakeRoleId1", "FakeRoleId2" };
- var controller = new CollorsController(new FakeDbContext());
- controller.ControllerContext = new ControllerContext() {
- Controller = controller,
- RequestContext = new RequestContext(new MockHttpContext(username, roles), new RouteData())
- };
- // Act
- var actionResult = controller.Index();
- var viewResult = actionResult as ViewResult;
- // Assert
- Assert.IsNotNull(viewResult);
- Assert.IsTrue(viewResult.ViewData.ContainsKey("Colours"));
- }
- private class MockHttpContext : HttpContextBase {
- private readonly IPrincipal user;
- public MockHttpContext(string username, string[] roles = null) {
- var identity = new GenericIdentity(username, string.Empty);
- var principal = new GenericPrincipal(identity, roles ?? new string[] { });
- user = principal;
- }
- public override IPrincipal User {
- get {
- return user;
- }
- set {
- base.User = value;
- }
- }
- }
- }
- var username = "[Test_Username_Here]";
- string[] roles = new[] { "FakeRoleId1", "FakeRoleId2" };
- var fake = Isolate.Fake.AllInstances<HttpContextBase>();
- var user = new ClaimsPrincipal(new GenericPrincipal(username, roles ?? new string[] { }));
- Isolate.WhenCalled(() => fake.User).WillReturn(user);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement