How do I write a unit test for controller use automapper? - asp.net-mvc

I'm trying to write a unit test for controller to test method return all users. But I confuse How can I write unit test with automapper
Controller :
private readonly IUserService _userService;
public UserController(IUserService userService)
{
this._userService = userService;
}
public ActionResult List()
{
var users = _userService.GetAllUsers().ToList();
var viewModel = Mapper.Map<List<UserViewModel>>(users);
return View(viewModel);
}
Controller Test:
private Mock<IUserService> _userServiceMock;
UserController objUserController;
List<UserViewModel> listUser;
[SetUp]
public void Initialize()
{
_userServiceMock = new Mock<IUserService>();
objUserController = new UserController(_userServiceMock.Object);
listUser = new List<UserViewModel>()
{
new UserViewModel() {Id = 1, Active = true, Password = "123456", UserName = "hercules"},
new UserViewModel() {Id = 2, Active = false, Password = "1234567", UserName = "alibaba"},
new UserViewModel() {Id = 3, Active = true, Password = "12345678", UserName = "robinhood"},
};
}
[Test]
public void Index_Returns_AllUser()
{
// How do I here ???
}

Configure automapper as you do on your MVC project:
[SetUp]
public void Initialize()
{
....
AutoMapperConfiguration.Configure();
}
Where AutoMapperConfiguration is a public static class like:
public class AutoMapperConfiguration
{
/// <summary>
/// Maps between VIEWMODEL and MODEL
/// </summary>
public static void Configure()
{
//maps here
Mapper.CreateMap..
}
}

You're trying to write a test of little to no value. Don't write this test. Use the real IUserService and use the real AutoMapper and assert against the ViewResult.
I would never unit test this code.
But if you're absolutely bent on writing this unit test, don't mock AutoMapper. Mock the IUserService.
UserController objUserController;
List<User> listUser;
[SetUp]
public void Initialize()
{
var userServiceMock = new Mock<IUserService>();
listUser = new List<User>()
{
new User() {Id = 1, Active = true, Password = "123456", UserName = "hercules"},
new User() {Id = 2, Active = false, Password = "1234567", UserName = "alibaba"},
new User() {Id = 3, Active = true, Password = "12345678", UserName = "robinhood"},
};
userServiceMock.Setup(framework => framework.GetAllUsers())
.Returns(listUser);
objUserController = new UserController(_userServiceMock.Object);
}
[Test]
public void Index_Returns_AllUser()
{
var result = objUserController.List();
var viewResult = result as ViewResult;
viewResult.ShouldNotBe(null);
var model = viewResult.Model as List<UserListModel>;
model.ShouldNotBe(null);
model.Count.ShouldBe(3); // Don't do more than this
}

You can create a wrapper class for automapper with an interface. For example:
public interface IMapperWrapper
{
object Map(object source, Type sourceType, Type destinationType);
}
Then all you need to do in your tests is mock your map.
automapperWrapperMock.Setup(x => x.Map, type, type);

Just setup your controller calling your Automapper configuration and all your tests for that controller will work properly.
[TestInitialize]
public void Setup()
{
controller = new yourController(_unitOfWork.Object, _someRepository.Object)
{
};
AutoMapperConfig.RegisterMappings();
}

Related

ReturnsAsync in Moq is not working

Here is my code
public interface IUserManager
{
Task<int> PostUser(User user);
IQueryable<User> GetUserById(long userId);
}
public class UserManager : IUserManager
{
public UserManager(DataContext context)
{
this.DataContext = context;
}
public async Task<int> PostUser(User user)
{
this.DataContext.User.Add(user);
return await this.DataContext.SaveChangesAsync().ConfigureAwait(false);
}
public IQueryable<User> GetUserById(long userId)
{
return this.DataContext.User
.Where(userNotes => userNotes.UserId == userId).AsQueryable();
}
}
Controller:
public class UserController : BaseController
{
private readonly IUserManager userManager;
public UserController()
{
this.userManager = new UserManager();
}
public UserController(IUserManager userManager)
{
this.userManager = userManager;
}
[EnableQuery]
public IQueryable<User> Get([FromODataUri]long userId)
{
return this.userManager.GetUserById(userId);
}
public HttpResponseMessage Post(User user)
{
if (userNote == null || !ModelState.IsValid)
{
return this.BuildErrorResponse(ResponseCodes.INVALID_MISSING_INPUTS);
}
if (this.userManager.PostUser(user).Result <= 0)
{
return this.BuildErrorResponse(ResponseCodes.USER_ADD_FAILED);
}
return this.BuildSuccessResponse<User>(ResponseCodes.USER_ADDED, user);
}
}
Moq test:
[TestClass]
public class UnitTest
{
IUserManager userManagerMock;
Mock<IUserManager> iUserManagerMock;
[TestInitialize]
public void Setup()
{
//.. setup variables and mock data
userManagerMock = new UserManager(ContextMock.Object);
iUserManagerMock.Setup(u => u.PostUser(It.IsAny<User>()))
.ReturnsAsync(1);
}
[TestMethod]
public void Post()
{
var controller = new UserController(userManagerMock); //userNotesManagerMock will have the mock data //and mock methods setup
var httpResponse = controller.Post(userPostMock); //userPostMock will have mock data to save
//Assert.AreEqual(HttpResponseMessage, result);
}
}
I wrote a post method as you'd see here. I've a Get method as well which is working perfectly with mocking data.
But when I debug through the Post, the data the following statement is always returns ZERO instead of 1, which I've set up in the ReturnsAsync.
this.userManager.PostUser(user).Result <= 0 //this always gives me zero
What's wrong with the post ? Am I doing anything wrong ?
Can anyone shed some light on this
EDIT
Here is the GET version of the Test method and setup
[TestInitialize]
public void Setup()
{
//dummy data setup
UserMock = new List<User>
{
new User { //blah blah properties }
}.AsQueryable();
//context setup
dbSetUserMock = new Mock<IDbSet<User>>();
dbSetUserMock.Setup(m => m.Provider).Returns(UserMock.Provider);
dbSetUserMock.Setup(m => m.Expression).Returns(UserMock.Expression);
dbSetUserMock.Setup(m => m.ElementType).Returns(UserMock.ElementType);
dbSetUserMock.Setup(m => m.GetEnumerator()).Returns(UserMock.GetEnumerator());
UserContextMock = new Mock<DataContext>();
UserContextMock.Setup(s => s.User).Returns(dbSetUserMock.Object);
//inject the context to manager
UserManagerMock = new UserManager(UserContextMock.Object);
iUserManagerMock = new Mock<IUserManager>();
iUserManagerMock.Setup(notes => notes.PostUserNote(It.IsAny<User>()))
.ReturnsAsync(1);
}
[TestMethod]
public void Get_User_Success()
{
var controller = new UserController(UserManagerMock);
var values = controller.Get(100);
Assert.AreEqual(100, values.FirstOrDefault().UserId);
}
Get_User_Success works well now with the dummy data set and I'm able to pass the test without iUserManagerMock object. Reason being I want to execute the code inside of GetUser() method in Manager class.
And I've another question over here. As I'm setting the expected result to be 1 in the ReturnAsync for Post action. How do I build a test method for failure case scenario as the return from the POST method will still be 1 for failure case ?
You are mixing up the set up. If the method under test is the UserController.Post and you want to mock the UserManager via the IUserManager interface, then you don't need to new one up manually.
[TestClass]
public class UnitTest {
[TestMethod]
public void UserController_Should_Post_User_Ok() {
//Arrange
var userPostMock = new User { UserId = 100 };
var userManagerMock = new Mock<IUserManager>();
userManagerMock.Setup(u => u.PostUser(It.IsAny<User>())).ReturnsAsync(1);
var controller = new UserController(userManagerMock.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
//Act
var httpResponse = controller.Post(userPostMock);
//Assert
Assert.AreEqual(System.Net.HttpStatusCode.OK, httpResponse.StatusCode);
}
[TestMethod]
public void UserController_Should_Post_User_Fail() {
//Arrange
var userPostMock = new User { UserId = 100 };
var userManagerMock = new Mock<IUserManager>();
userManagerMock.Setup(u => u.PostUser(It.IsAny<User>())).ReturnsAsync(0);//Replicating a failed post
var controller = new UserController(userManagerMock.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
//Act
var httpResponse = controller.Post(userPostMock);
//Assert
Assert.AreEqual(System.Net.HttpStatusCode.InternalServerError, httpResponse.StatusCode);
}
[TestMethod]
public void UserManager_Should_Get_User_Success() {
//Arrange
var userMock = new List<User>
{
new User (){ UserId=100 }
}.AsQueryable();
//context setup
var dbSetUserMock = new Mock<IDbSet<User>>();
dbSetUserMock.Setup(m => m.Provider).Returns(userMock.Provider);
dbSetUserMock.Setup(m => m.Expression).Returns(userMock.Expression);
dbSetUserMock.Setup(m => m.ElementType).Returns(userMock.ElementType);
dbSetUserMock.Setup(m => m.GetEnumerator()).Returns(userMock.GetEnumerator());
var userContextMock = new Mock<DataContext>();
userContextMock.Setup(s => s.User).Returns(dbSetUserMock.Object);
//inject the context to manager
var userManagerMock = new UserManager(userContextMock.Object);
//Act
var values = userManagerMock.GetUserById(100);
//Assert
Assert.AreEqual(100, values.FirstOrDefault().UserId);
}
}

How to mock data for HttpContext NUnit

I have written a test class for my controller class using NUnit and Moq framework.My classes are following
public class ClientTypeController : BaseController
{
IClientTypeService clientTypeService;
IClientTypeAudService clientTypeAudService;
IClientTypeHisService clientTypeHisService;
IUserAccountService userAccountService;
System.Web.HttpResponseBase _responceBase;
public ClientTypeController()
{
}
public ClientTypeController(IClientTypeService _IClientTypeService, IClientTypeAudService _IClientTypeAudService,
IClientTypeHisService _IClientTypeHisService,IUserAccountService
_IUserAccountService)
{
clientTypeService = _IClientTypeService;
clientTypeAudService = _IClientTypeAudService;
clientTypeHisService = _IClientTypeHisService;
userAccountService = _IUserAccountService;
}
public ClientTypeController(IClientTypeAudService _clientTypeAudService,
System.Web.HttpResponseBase responceBas)
{
clientTypeAudService = _clientTypeAudService;
this._responceBase = responceBas;
}
......
.....
And my test class for the above given controller class,
public class ClientTypeControllerTest
{
private Mock<IClientTypeService> _clientTypeServiceMock;
private Mock<IClientTypeAudService> _clientTypeAudServiceMock;
private Mock<IClientTypeHisService> _clientTypeHisServiceMock;
private Mock<HttpSessionStateBase> _sessionMock;
private Mock<HttpResponseBase> _httpresponceMock;
private Mock<IUserAccountService> _userAccountService;
ClientTypeController objClientTypeController;
protected Users LoggedInUser { get; set; }
List<ClientTypeAud> lists;
[SetUp]
public void Initialize()
{
//System.Diagnostics.Debugger.Launch();
_clientTypeServiceMock = new Mock<IClientTypeService>();
_clientTypeAudServiceMock = new Mock<IClientTypeAudService>();
_clientTypeHisServiceMock = new Mock<IClientTypeHisService>();
_userAccountService = new Mock<IUserAccountService>();
_sessionMock = new Mock<HttpSessionStateBase>();
_httpresponceMock = new Mock<HttpResponseBase>();
var ctrlContext = new Mock<ControllerContext>();
AutoMapperConfiguration.Configure();
_sessionMock.SetupGet(s => s["LOGGED_IN_USER"]).Returns(users);
ctrlContext.Setup(p => p.HttpContext.Session).Returns(_sessionMock.Object);
}
[Test]
public void Show_AllClientTypeRecords_InGridView_UnitTest()
{
lists = new List<ClientTypeAud>() {
new ClientTypeAud() { Id = 1, CTypeName = "INR", CompanyId = 1, Active = "Y" },
new ClientTypeAud() { Id = 1, CTypeName = "ABC", CompanyId = 1, Active = "Y" },
new ClientTypeAud() { Id = 1, CTypeName = "AVM", CompanyId = 1, Active = "Y" }
};
_clientTypeAudServiceMock.Setup(x => x.All()).Returns(lists.AsQueryable());
objClientTypeController = new ClientTypeController(_clientTypeServiceMock.Object,
_clientTypeAudServiceMock.Object, _clientTypeHisServiceMock.Object,
_userAccountService.Object);
var result = objClientTypeController.GridData("", "asc", 1, 1) as JsonResult;
Assert.IsNotNull(result.Data);
}
}
And my BaseController class is ,
public class BaseController : Controller
{
public SessionProvider SessionProvider;
protected Users LoggedInUser { get; set; }
public string actionName { get; set; }
protected string controllerName { get; set; }
protected string area { get; set; }
public BaseController()
{
actionName =
System.Web.HttpContext.Current.Request.RequestContext.RouteData.GetRequiredString("action");
controllerName =
System.Web.HttpContext.Current.Request.RequestContext.RouteData.
GetRequiredString("controller");
SessionProvider = new SessionProvider(Session);
LoginMethod();
ViewBag.Menu = BuildMenu();
}
......
......
When I run my test class using NUnit then it shows Nullreferenceexception was unhandled by user code on
actionName = System.Web.HttpContext.Current.Request.RequestContext.
RouteData.GetRequiredString("action");
This is in my BaseControllerClass. So I don't know how to Moq the data for HttpContext.Current.Request.RequestContext.so please Can anyone please help to find the solution
You should create wrapper utility for handling the HttpContext.
This wrapper should implement an interface and in your UT you should mock that call (you can use Rhino Mocks).

How to get result from ControllerContext

My controller action returns a custom ActionResult that executes either a success or failure result depending on some validation logic. This happens within ExecuteResult.
My question is, how can I check the result?
Here's the test so far:
[TestFixture]
public class FormActionResultTests
{
TestController controller;
[SetUp]
public void SetUp()
{
ObjectFactory.Initialize(cfg =>
{
cfg.For<IFormHandler<TestModel>>().Use<TestModelHandler>();
});
controller = new TestControllerBuilder().CreateController<TestController>();
}
[Test]
public void Valid_input_returns_success_result()
{
var result = controller.Test(new TestModel { IsValid = true, IsValid2 = true })
.AssertResultIs<FormActionResult<TestModel>>();
var context = controller.ControllerContext;
result.ExecuteResult(context);
// how to verify result?
}
}
public class TestController : Controller
{
public ActionResult Test(TestModel model) {
return new FormActionResult<TestModel>(model, this.Content("Success"), View(model));
}
}
public class TestModel {
public bool IsValid { get; set; }
public bool IsValid2 { get; set; }
}
public class TestModelHandler : IFormHandler<TestModel>
{
public void Handle(TestModel form, IValidationDictionary validationDictionary)
{
}
}
Update
Here's what worked for me in the end (using NSubstitute):
[Test]
public void Valid_input_returns_success_result()
{
var result = new FormActionResult<TestModel>(new TestModel { IsValid = true, IsValid2 = true },
new ContentResult { Content = "Success" }, new ContentResult { Content = "Failed" });
var sb = new StringBuilder();
var response = Substitute.For<HttpResponseBase>();
response.When(x => x.Write(Arg.Any<string>())).Do(ctx => sb.Append(ctx.Arg<string>()));
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Response.Returns(response);
var controllerContext = new ControllerContext(httpContext, new RouteData(), new TestController());
result.ExecuteResult(controllerContext);
sb.ToString().ShouldEqual("Success");
}
Controller should be tested that they return correct ActionResult in your case, and the Success or Failure of ActionResult should be tested by ActionResultTest and it has nothing to do with controller. Unit test means single unit test - but you test both controller and ActionResult in the same test, that is incorrect. To test ActionResult, first imagine that generally all that ActionResult does, is writing result to HttpResponse. Let's rewrite your code to use Moq to supply StringWriter for ControllerContext.HttpContext.HttpResponse.Output
[Test]
public void Valid_input_returns_success_result()
{
var result = controller.Test(new TestModel { IsValid = true, IsValid2 = true })
.AssertResultIs<FormActionResult<TestModel>>();
var context = controller.ControllerContext;
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
StringWriter actionResultOutput = new StringWriter();
mockHttpContext.Setup(x => x.Response.Output).Returns(actionResultOutput);
context.HttpContext = mockHttpContext.Object;
result.ExecuteResult(context);
// how to verify result? Examine actionResultOutput
}
All is left to examine actionResultOutput. For example, if your action result is designed to return string "Success" when validation is ok and "Error" when validation failed, compare these strings to actionResultOutput.ToString(). If your result view's generated html is more complex, you can use HtmlAgilityPack to examine output more deeply
You should write a simple unit test of the Test-action, asserting on the returned action result. You shouldn't depend on the MVC framework in your test. Simply create a new instance of TestController and call the Test method.

Moq Roles.AddUserToRole test

I am writing unit tests for a project in ASP.NET MVC 1.0 using Moq and MvcContrib TestHelper classes. I have run into a problem.
When I come to Roles.AddUserToRole in my AccountController, I get a System.NotSupportedException. The Roles class is static and Moq cannot mock a static class.
What can I do?
You could use a pattern like DI (Dependency Injection). In your case, I would pass a RoleProvider to the AccountController, which would be the default RoleProvider by default, and a mock object in your tests. Something like:
public class AccountController
{
private MembershipProvider _provider;
private RoleProvider roleProvider;
public AccountController()
: this(null, null)
{
}
public AccountController(MembershipProvider provider, RoleProvider roleProvider)
{
_provider = provider ?? Membership.Provider;
this.roleProvider = roleProvider ?? System.Web.Security.Roles.Provider;
}
}
The MVC runtime will call the default constructor, which in turn will initialize the AccountController with the default role provider. In your unit test, you can directly call the overloaded constructor, and pass a MockRoleProvider (or use Moq to create it for you):
[Test]
public void AccountControllerTest()
{
AccountController controller = new AccountController(new MockMembershipProvider(), new MockRoleProvider());
}
EDIT: And here's how I mocked the entire HttpContext, including the principal user.
To get a Moq version of the HttpContext:
public static HttpContextBase GetHttpContext(IPrincipal principal)
{
var httpContext = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = principal;
httpContext.Setup(ctx => ctx.Request).Returns(request.Object);
httpContext.Setup(ctx => ctx.Response).Returns(response.Object);
httpContext.Setup(ctx => ctx.Session).Returns(session.Object);
httpContext.Setup(ctx => ctx.Server).Returns(server.Object);
httpContext.Setup(ctx => ctx.User).Returns(user);
return httpContext.Object;
}
A mock implementation of Principal:
public class MockPrincipal : IPrincipal
{
private IIdentity _identity;
private readonly string[] _roles;
public MockPrincipal(IIdentity identity, string[] roles)
{
_identity = identity;
_roles = roles;
}
public IIdentity Identity
{
get { return _identity; }
set { this._identity = value; }
}
public bool IsInRole(string role)
{
if (_roles == null)
return false;
return _roles.Contains(role);
}
}
A MockIdentity:
public class MockIdentity : IIdentity
{
private readonly string _name;
public MockIdentity(string userName) {
_name = userName;
}
public override string AuthenticationType
{
get { throw new System.NotImplementedException(); }
}
public override bool IsAuthenticated
{
get { return !String.IsNullOrEmpty(_name); }
}
public override string Name
{
get { return _name; }
}
}
And the magic call:
MockIdentity identity = new MockIdentity("JohnDoe");
var httpContext = MoqHelpers.GetHttpContext(new MockPrincipal(identity, null));
Note that I edited the code above to leave out some custom stuff, but I'm quite sure this should still work.
Now I run into another problem when I try to test the ChangePassword() method in ASP.NET MVC.
try
{
if (MembershipService.ChangePassword(User.Identity.Name, currentPassword, newPassword))
{
if (!TempData.ContainsKey("ChangePassword_success"))
{
TempData.Add("ChangePassword_success", true);
}
return PartialView("ChangePassword");
}
Now I get that User is null, when I reach this line. In my testclass I have:
mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);
I thought that this would work, but it doesn't care for that I send "johndoe". And If I were to mock IPrincipal, the User property is readonly.
TypeMock Isolator does mocking of statics etc. But I second (and +1'd) Razzie's answer.
I have done what you coded, but I still get that User is null when it reaches:
mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);
In my Testclass I have:
//Arrange (Set up a scenario)
var mockMembershipService = new Mock<IMembershipService>();
MockIdentity identity = new MockIdentity("JohnDoe");
var httpContext = MoqHelpers.GetHttpContext(new MockPrincipal(identity, null));
var controller = new AccountController(null, mockMembershipService.Object, null, null, null);
string currentPassword = "qwerty";
string newPassword = "123456";
string confirmPassword = "123456";
// Expectations
mockMembershipService.Setup(pw => pw.MinPasswordLength).Returns(6);
mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);
Do I call my cp.ChangePassword with wrong parameters? And should MVCContrib Testhelpers classes be able to mock Http context and so on? I just can't find info for how to setup User.Identity.Name with MVCContrib.
I have used this from a tutorial to test something (mock) session:
var builder = new TestControllerBuilder();
var controller = new AccountController(mockFormsAuthentication.Object, mockMembershipService.Object, mockUserRepository.Object, null, mockBandRepository.Object);
builder.InitializeController(controller);
EDIT: I have come a little further:
MockIdentity identity = new MockIdentity("JohnDoe");
var httpContext = MoqHelpers.GetHttpContext(new MockPrincipal(identity, null));
var controller = new AccountController(null, mockMembershipService.Object, null, null, null);
controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);
but my now I can't get my cp.ChangePassword in the expectation to return true:
mockMembershipService.Setup(cp => cp.ChangePassword("johndoe", currentPassword, newPassword)).Returns(true);
I am sending "johndoe" string, because, it requires a string as a parameter for User.Identity.Name, but it doesn't return true.

Mocking a Customer SessionHandler Object in ASP.NET MVC for Unittests with Rhino Mocks

I currently use the following approach to create a strongly typed object representing session variables.
public abstract class SessionController : Controller
{
private const string SESSION_NAME = "UserSession";
public SessionData SessionData
{
get
{
SessionData sessionData = (SessionData)Session[SESSION_NAME];
if (sessionData != null)
{
return sessionData;
}
else
{
sessionData = new SessionData();
Session[SESSION_NAME] = sessionData;
return sessionData;
}
}
set
{
Session[SESSION_NAME] = value;
}
}
}
SessionData is a simple object like for example
[Serializable]
public class SessionData
{
public String SessionId { get; set; }
public Int64 UserId { get; set; }
public String NameOfUser { get; set; }
}
When creating a new Controller I derivate it from the SessionController so that I have strongley typed access to my SessionData. For example
public CityController : SessionController
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
ViewData.Model = _cityService.GetAll(SessionData.UserId);
return View("Index");
}
}
So, I am struggling at the moment to get this approached covered by a unittest. A shortened version of what I have tried is the following snippet
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
_cityService = MockRepository.GenerateStub<ICityService>();
_sesssionData = new SessionData { UserId = 1, SessionId = "1" };
// First Approach
controller = new CityController(_cityService);
controller.Expect(p => p.SessionData).Return(_sesssionData);
// Second Approach
cctx = MockRepository.GenerateStub<ControllerContext>();
cctx.Expect(p=>p.HttpContext.Session["UserSession"] as SessionData).Return(_sesssionData);
controller.ControllerContext = cctx;
}
Has anyone a tip on how to get this problem solved?
If you make your SessionData property virtual then your first approach could work:
// Arrange
var mocks = new MockRepository();
var cityService = MockRepository.GenerateStub<ICityService>();
var sesssionData = new SessionData { UserId = 1, SessionId = "1" };
var controller = mocks.PartialMock<CityController>(cityService);
controller.Expect(c => c.SessionData).Return(sessionData);
controller.Replay();
// Act
controller.Index();
//Assert
...
IMO this approach is not very good because the SUT (Subject Under Test => in this case CityController) is being mocked with PartialMock.

Resources