How to mock viewModel when test controller? - c#

I have to test my controller as below
[HttpGet]
[Route("")]
[HandleError(View= "Error")]
public ActionResult Index(string name)
{
return View("Index", new MyViewModel){
Name = name,
Link = Request.UrlReferrer
}
}
and my ViewModel is as below
public class MyViewModel{
public string Name{get;set;}
public Uri Link{get;set}
}
My problem is, when I write a unit test as below, the controller.Index(name) always return null, it seems because I didn't mock ViewModel? But how I mock the ViewModel as it is inside the function?
My purpose is to test if the name is passed into the ViewModel properly, I think I should not mock MyViewModel, is that correct?
Also, as this is HttpGet, should I mock the Http Request? I'm not sure how to test the Http Request in MVC.NET
[TestMethod]
public void Index_Return_ViewModel(){
string name = "name";
var controller = new MyController(foo, bar);
var result = controller.Index(name) as ViewResult;
var viewModel = controller.ViewData.Model as MyViewModel;
Assert.AreEqual("Index", result.ViewName);
}

Using the following example controller
public class MyController : Controller {
[HandleError(View = "Error")]
public ActionResult Index(string name) {
return View("Index", new MyViewModel() {
Name = name,
Link = Request.UrlReferrer
});
}
}
for the purposes of explaining the answer.
Because the action accesses the Request.UrlReferrer, the unit test would need to provide the necessary dependencies for the test to be exercised to completion.
For example
[TestMethod]
public void Index_Return_ViewModel() {
//Arrange
var link = new Uri("http://example.com");
var mockContext = new Mock<ControllerContext>();
mockContext.Setup(_ => _.HttpContext.Request.UrlReferrer)
.Returns(link);
string name = "name";
var controller = new MyController() {
ControllerContext = mockContext.Object
};
//Act
var result = controller.Index(name) as ViewResult;
//Assert
Assert.AreEqual("Index", result.ViewName);
var viewModel = controller.ViewData.Model as MyViewModel;
Assert.IsNotNull(viewModel);
Assert.AreEqual(name, viewModel.Name);
Assert.AreEqual(link, viewModel.Link);
}
There was no need to mock the view model. The action can be confirmed to behave as expected by comparing the returned model properties to the expected values.

Related

How to Unit Test a GlassController Action which Returns a View Taking a Model

I'm a sitecore developer and I want to create a sample sitecore helix unit testing project for testing out our "HomeBottomContentController" controller:
public class HomeBottomContentController : GlassController
{
private readonly ISitecoreContext _iSitecoreContext;
public HomeBottomContentController(ISitecoreContext iSitecoreContext)
{
_iSitecoreContext = iSitecoreContext;
}
public override ActionResult Index()
{
var model = _iSitecoreContext.GetCurrentItem<Home_Control>();
return View("~/Views/HomeBottomContent/HomeBottomContent.cshtml", model);
}
}
I have created a WTW.Feature.HomeBottomContent.Tests project, for the purpose of testing this entire component using helix unit testing. In it I have a UnitTest1.cs file with following:
namespace WTW.Feature.HomeBottomContent.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Test_ISitecoreContextInsertion()
{
var iSitecoreContext = Mock.Of<Glass.Mapper.Sc.ISitecoreContext>();
HomeBottomContentController controllerUnderTest = new HomeBottomContentController(iSitecoreContext);
var result = controllerUnderTest.Index() as ViewResult;
Assert.IsNotNull(result);
}
}
}
This test does pass, meaning "result" is NOT null; however, the problem is when I step into the Index() code, I see that the "model" variable is NULL when we do
var model = _iSitecoreContext.GetCurrentItem<Home_Control>();
My question is, how exactly do I change this code to make sure that the "model" in that line does not become null? How do I "mock" an item in unit test code for the _iSitecoreContext so that it has a "Home_Control" template with legit values for its fields? Would that even be the right approach? Most online sources I've found do not have a similar scenario, I'm looking for the shortest code possible.
Another question I had is, how can I test the below Index() method in my [TestMethod], given that the SitecoreContext is declared inside the Index() method, rather than received in the HomeBottomContentController constructor like above? Is there a way to do that from the [TestMethod], or we have to send in the SitecoreContext into the HomeBottomContentController constructor or into the Index() method as a parameter?
public override ActionResult Index()
{
var context = new SitecoreContext();
var model = context.GetCurrentItem<Home_Control>();
return View("~/Views/HomeBottomContent/HomeBottomContent.cshtml", model);
}
In that case you would need to mock the desired behavior on the mocked dependency
[TestClass]
public class UnitTest1 {
[TestMethod]
public void Test_ISitecoreContextInsertion() {
//Arrange
var model = new Home_Control() {
//...populate as needed
}
var iSitecoreContext = new Mock<Glass.Mapper.Sc.ISitecoreContext>();
//Setup the method to return a model when called.
iSitecoreContext.Setup(_ => _.GetCurrentItem<Home_Control>()).Returns(model);
var controllerUnderTest = new HomeBottomContentController(iSitecoreContext.Object);
//Act
var result = controllerUnderTest.Index() as ViewResult;
//Assert
Assert.IsNotNull(result);
Assert.IsNotNull(result.Model);
//...other assertions.
}
}
UPDATE
Creating the context within the action tightly couples it to the context, making it almost impossible to mock. That is the reason explicit dependencies are injected
You can do something like that:
public class HomeBottomContentController : GlassController
{
private readonly ISitecoreContext _iSitecoreContext;
public HomeBottomContentController(ISitecoreContext iSitecoreContext)
{
_iSitecoreContext = iSitecoreContext;
}
public override ActionResult Index()
{
var model = this.GetCurrentItem();
return View("~/Views/HomeBottomContent/HomeBottomContent.cshtml", model);
}
protected virtual Home_Control GetCurrentItem()
{
return _iSitecoreContext.GetCurrentItem<Home_Control>();
}
}
namespace WTW.Feature.HomeBottomContent.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Test_ISitecoreContextInsertion()
{
var iSitecoreContext = Mock.Of<Glass.Mapper.Sc.ISitecoreContext>();
var controllerUnderTest = new FakeHomeBottomContentController(iSitecoreContext);
var result = controllerUnderTest.Index() as ViewResult;
Assert.IsNotNull(result);
}
}
public class FakeHomeBottomContentController : HomeBottomContentController
{
public FakeHomeBottomContentController(ISitecoreContext iSitecoreContext) : base(iSitecoreContext)
{
}
protected override Home_Control GetCurrentItem()
{
// return instance of Home_Control type
// e.g.
return new Home_Control();
}
}
}

Unit Test - Assert object returned by a controller action

How can I check if the value returned as part of that OkObjectResult has a count of 2 without changing any code in the controller action?
Here is my controller action
public IActionResult GetUserNames()
{
var users = _repository.GetUsers();
return Ok(users.Select(u => u.Name));
}
My unit test looks like this
[Fact]
public void GetUserNames_ValidRequest_ShouldReturnOk()
{
_repository
.Setup(r => r.GetUsers())
.Return(new List<User>
{
new User { Name = "SomeRandomName" },
new User { Name = "SomeRandomName2" }
});
var result = _controller.GetUserNames();
result.Should().BeOfType<OkObjectResult>();
// Code to check if 2 names are returned
}
I am using Mock and FluentAssertions in my unit test.
You should be able to do something like this:
var objectResult = Assert.IsType<OkObjectResult>(result);
var model = Assert.IsAssignableFrom<List<string>>(objectResult.Value);
Assert.Equal(2, model.Count);

How to Unit test a method using Moqs which create session

How to test a method which creates session inside the method. i using to do Unit test . when i call method using test case it was unable to create session inside method. can anyone please help me to create unit tests for my code below
public ActionResult InviteUser(string Id)
{
if (!string.IsNullOrEmpty(Id))
{
Session["verification_uid"] = Id;
return RedirectToAction("Login", "Account");
}
return View();
}
i have tried with following code also but it not working
[TestMethod]
public void InviteUser_ExpectRedirectActionResultReturned()
{
//Arrange
controller = new AccountController();
var mockControllerContext = new Mock<ControllerContext>();
var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupGet(s => s["verification_uid"]).Returns("123"); //somevalue
mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);
controller.ControllerContext = mockControllerContext.Object;
var id = "1";
System.Web.HttpContext.Current.Session["verification_uid‌​ID"] = "12";
//Act
var result = (RedirectToRouteResult)controller.InviteUser(id);
//Assert
result.RouteValues["action"].Equals("Index");
result.RouteValues["controller"].Equals("Home");
Assert.AreEqual("Index", result.RouteValues["action"]);
Assert.AreEqual("Home", result.RouteValues["controller"]);
}
You could put the setting of the session variable into a helper class, implementing an interface that gets passed into the class which you could mock in the unit test.
public MyClass
{
private readonly ISessionHelper _helper;
public MyClass(ISessionHelper helper)
{
this._helper = helper;
}
public ActionResult InviteUser(string Id)
{
if (!string.IsNullOrEmpty(Id))
{
this._helper.SetSessionVariable("verification_uid", Id);
return RedirectToAction("Login", "Account");
}
return View();
}
}
Your helper would contain SetSessionVariable which does the setting.
Then, in your unit test, you mock ISessionHelper.

Mocking method used in controller action

public ActionResult SomeAction(int?id)
{
MyModel model = new MyModel();
return View(model);
}
[Test]
public void Can_Open_SomeAction()
{
// controller is already set inside `SetUp` unit step.
ViewResult res = this.controller.SomeAction() as ViewResult;
var model = result.Model as MyModel;
Assert.IsNotNull(model);
}
this test passes succ. but when when change controller action to have populate combos like
public ActionResult SomeAction(int?id)
{
MyModel model = new MyModel();
this.PopulatePageCombos(id);
return View(model);
}
I'm getting error on line this.PopulatePageCombos(id);
Object reference is not set
So, how can I mock this PopulatePageCombos method in unit test?
Update:
public ActionResult SomeAction(int?id)
{
MyModel model = new MyModel();
this.PopulatePageCombos(model.Id, 100);
return View(model);
}
Update 2:
PopulatePageCombos (model, countryId, requesterId);
where model is of type MyModel, countryId is int and requesterId is int
You can create a helper class PopulatePageCombosHelper and encapsulate PopulatePageCombos method in it. So the SomeAction method would look like
public PopulatePageCombosHelper populatePageHelper;
public ActionResult SomeAction(int?id)
{
MyModel model = new MyModel();
populatePageHelper.PopulatePageCombos(id);
return View(model);
}
So then you can mock populatePageHelper
[Test]
public void Can_Open_SomeAction()
{
// controller is already set inside `SetUp` unit step.
var populatePageHelperMock = new Mock<PopulatePageCombosHelper>();
controller.populatePageHelper = populatePageHelperMock;
ViewResult res = this.controller.SomeAction() as ViewResult;
var model = result.Model as JobCreate;
//...
Assert.IsNotNull(model);
}
You can make PopulatePageCombos method virtual and override it in derived class ControllerTestable and test the ControllerTestable
public class ControllerTestable : Controller
{
public bool IsCalled = false;
public override ViewResult SomeAction()
{
IsCalled = true;
return null;
}
}
So in the test instead of creating Controller controller you can create ControllerTestable controller.
[Setup]
public void SetUp ()
{
var controller = new ControllerTestable();
//...
}
[Test]
public void Can_Open_SomeAction()
{
// controller is already set inside `SetUp` unit step.
ViewResult res = this.controller.SomeAction() as ViewResult;
var model = result.Model as JobCreate;
//...
Assert.IsTrue(controller.IsCalled);
Assert.IsNotNull(model);
}
You can partial mock the controller. Having:
public virtual void PopulatePageCombos(int? id)
{
throw new NullReferenceException();
}
public ActionResult SomeAction(int? id)
{
MyModel model = new MyModel();
this.PopulatePageCombos(id);
return View(model);
}
Then you setup the method PopulatePageCombos to do anything:
public class Default1ControllerTests
{
private Mock<Default1Controller> controllerMock;
[SetUp]
public void SetUp()
{
this.controllerMock = new Mock<Default1Controller>() { CallBase = true };
this.controllerMock.Setup(m => m.PopulatePageCombos(It.IsAny<int?>())).Callback(() => { });
}
[Test]
public void Can_Open_SomeAction()
{
// controller is already set inside `SetUp` unit step.
ViewResult res = this.controllerMock.Object.SomeAction(null) as ViewResult;
var model = res.Model as MyModel;
Assert.IsNotNull(model);
}
}
It's important to declare virtual the method to mock and specify CallBase = true on mock creation. This will call the programmed logic on methods not setup.

Mock Request Object for Web API unit test

I want to unit test my web API controller. I have a problem with one of my action method (POST) which is need value from Request object, to get the controller name.
I'm using NSubtitute, FluentAssertions to support my unit test
This is my controller code looks like:
public class ReceiptsController : BaseController
{
public ReceiptsController(IRepository<ReceiptIndex> repository) : base(repository) { }
..... Other action code
[HttpPost]
public IHttpActionResult PostReceipt(string accountId, [FromBody] ReceiptContent data, string userId = "", string deviceId = "", string deviceName = "")
{
if (data.date <= 0)
{
return BadRequest("ErrCode: Save Receipt, no date provided");
}
var commonField = new CommonField()
{
AccountId = accountId,
DeviceId = deviceId,
DeviceName = deviceName,
UserId = userId
};
return PostItem(repository, commonField, data);
}
}
And the base class for my controller :
public abstract class BaseController : ApiController
{
protected IRepository<IDatabaseTable> repository;
protected BaseController(IRepository<IDatabaseTable> repository)
{
this.repository = repository;
}
protected virtual IHttpActionResult PostItem(IRepository<IDatabaseTable> repo, CommonField field, IContent data)
{
// How can I mock Request object on this code part ???
string controllerName = Request.GetRouteData().Values["controller"].ToString();
var result = repository.CreateItem(field, data);
if (result.Error)
{
return InternalServerError();
}
string createdResource = string.Format("{0}api/accounts/{1}/{2}/{3}", GlobalConfiguration.Configuration.VirtualPathRoot, field.AccountId,controllerName, result.Data);
var createdData = repository.GetItem(field.AccountId, result.Data);
if (createdData.Error)
{
return InternalServerError();
}
return Created(createdResource, createdData.Data);
}
}
And this is my unit test for success create scenario:
[Test]
public void PostClient_CreateClient_ReturnNewClient()
{
// Arrange
var contentData = TestData.Client.ClientContentData("TestBillingName_1");
var newClientId = 456;
var expectedData = TestData.Client.ClientData(newClientId);
clientsRepository.CreateItem(Arg.Any<CommonField>(), contentData)
.Returns(new Result<long>(newClientId)
{
Message = ""
});
clientsRepository.GetItem(accountId, newClientId)
.Returns(new Result<ContactIndex>(expectedData));
// Act
var result = _baseController.PostClient(accountId, contentData, userId);
// Asserts
result.Should().BeOfType<CreatedNegotiatedContentResult<ContactIndex>>()
.Which.Content.ShouldBeEquivalentTo(expectedData);
}
I don't know if there is any way to extract Request object from the controller, or maybe is there any way to mock it on the unit test?
Right now this code Request.GetRouteData() return null on the unit test.
you can make an interface for getting Request Data(pass Request object to it). Implement that interface and use as dependency in your Controller. Then you can easily mock this interface implementation in your unit tests.
I've finally find a way to solve this. So basically I have to create some configuration related stuff to make my unit test works.
I create a helpers class for this
public static class Helpers
{
public static void SetupControllerForTests(ApiController controller)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/products");
var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "products" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
}
Then passing my test controller on my test setup
[SetUp]
public void SetUp()
{
clientsRepository = Substitute.For<IRepository<ContactIndex>>();
_baseController = new ClientsController(clientsRepository);
Helpers.SetupControllerForTests(_baseController);
}
I don't know if this is a best way to do it, but I prefer this way instead of create a new interface and inject it to my controller.

Categories