I am new to Unit Testing and am trying to create some Xunit tests for my Web API Controller's POST method.
Here is my Controller's POST method:
[HttpPost("")]
public async Task<IActionResult> CreateArea([FromBody] AreaForCreationDto area)
{
// Check that the 'area' object parameter can be de-serialised to a AreaForCreationDto.
if (area == null)
{
var message = "Could not de-serialise the request body to an AreaForCreationDto object";
_logger.LogError(message);
// Return an error 400.
return BadRequest(message);
}
/*
* ModelState.IsValid is determined by the attributes associated with the
* Data Annotations on the properties of the ViewModel.
*/
if (!ModelState.IsValid)
{
// Return a response with a Status Code 422.
return new UnprocessableEntityObjectResult(ModelState);
};
// Map a AreaForCreationDto object to a Area entity.
var areaEntityToAdd = _mapper.Map<Area>(area);
// Call the repository to add the new Area entity to the DbContext.
_areaRepository.AddArea(areaEntityToAdd);
// Save the new Area entity, added to the DbContext, to the SQL database.
if (await _areaRepository.SaveChangesAsync())
{
// Note: AutoMapper maps the values of the properties from the areaEntityToAdd
// to a new areaToReturn object.
// This ensures that we don't expose our Area entity to the web browser.
var areaToReturn = _mapper.Map<AreaDto>(areaEntityToAdd);
// Return a 201 'created' response along with the location URL in the
// response Header.
return CreatedAtRoute("GetArea",
new { id = areaToReturn.Id },
areaToReturn);
}
else {
// The save failed.
var message = $"Could not save new Area {areaEntityToAdd.Id} to the database.";
_logger.LogWarning(message);
throw new Exception(message);
};
}
The first Unit Test I have written is intended to ensure that on sending a POST request, with an object which can be de-serialised into an AreaForCreation object, the function returns a 201 CreatedAtRouteResult along with the new Area which has been created.
Here is the Xunit test:
[Fact]
public void ReturnAreaForCreateArea()
{
//Arrange
var _mockAreaRepository = new Mock<IAreaRepository>();
_mockAreaRepository
.Setup(x => x.AddArea(testArea));
var _mockMapper = new Mock<IMapper>();
_mockMapper
.Setup(_ => _.Map<Area>(It.IsAny<AreaForCreationDto>()))
.Returns(testArea);
var _mockLogger = new Mock<ILogger<AreasController>>();
var _sut = new AreasController(_mockAreaRepository.Object, _mockLogger.Object, _mockMapper.Object);
// Act
var result = _sut.CreateArea(testAreaForCreationDto);
// Assert
Assert.NotNull(result);
var objectResult = Assert.IsType<CreatedAtRouteResult>(result);
var model = Assert.IsAssignableFrom<AreaDto>(objectResult.Value);
var areaDescription = model.Description;
Assert.Equal("Test Area For Creation", areaDescription);
}
I am getting an exception thrown when the unit test tries to Assert.IsType<CreatedAtRouteResult>(result). Debugging revealed that the Controller was failing to save to the repository. My AreaRepository has the following AddArea function which does not return a value so I assume that my _mockAreaRepository does not require a Return condition set (could be wrong here).
Do I need to configure my mockAreasRepository for the outcome of calling SaveChangesAsync()?
Yes because it is async you need to mock the return of a completed task to allow the method
await _areaRepository.SaveChangesAsync()
to be able to continue.
You also need to update the test to be async as well by returning a Task and await the method under test.
[Fact]
public async Task ReturnAreaForCreateArea() { //<-- note test is now async as well
//Arrange
var _mockAreaRepository = new Mock<IAreaRepository>();
_mockAreaRepository
.Setup(x => x.AddArea(testArea));
_mockAreaRepository
.Setup(x => x.SaveChangesAsync())
.ReturnsAsync(true); //<-- returns completed Task<bool> when invoked
var _mockMapper = new Mock<IMapper>();
_mockMapper
.Setup(_ => _.Map<Area>(It.IsAny<AreaForCreationDto>()))
.Returns(testArea);
_mockMapper
.Setup(_ => _.Map<AreaDto>(It.IsAny<Area>()))
.Returns(testAreaDto);
var _mockLogger = new Mock<ILogger<AreasController>>();
var _sut = new AreasController(_mockAreaRepository.Object, _mockLogger.Object, _mockMapper.Object);
// Act
var result = await _sut.CreateArea(testAreaForCreationDto);//<-- await
// Assert
Assert.NotNull(result);
var objectResult = Assert.IsType<CreatedAtRouteResult>(result);
var model = Assert.IsAssignableFrom<AreaDto>(objectResult.Value);
var areaDescription = model.Description;
Assert.Equal("Test Area For Creation", areaDescription);
}
Related
I'm trying to mock up an HttpContextWrapper for an API controller method that is supposed to return the UserHostAddress. I have no control over the implementation. I am only supposed to unit test the code that I have been given.
I have followed some examples already on StackOverflow, and while I have come closer to achieving what I need, I can't get past this exception:
Moq.MockException : HttpContextBase.ApplicationInstance invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
Here are my unit test methods:
private static HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
{
var request = new HttpRequestMessage();
var baseRequest = new Mock<HttpRequestBase>(MockBehavior.Strict);
var baseContext = new Mock<HttpContextBase>(MockBehavior.Strict);
baseRequest.Setup(br => br.UserHostAddress).Returns("127.0.0.1");
baseContext.Setup(bc => bc.Request).Returns(baseRequest.Object);
var baseContextWrapper = new Mock<HttpContextWrapper>(baseContext.Object.ApplicationInstance.Context);
request.RequestUri = new Uri(url);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
request.Properties.Add("MS_HttpContext", baseContextWrapper.Object);
request.Method = method;
return request;
}
[Test]
public void IsClientIpAddressReturned()
{
// Assign
var request = CreateRequest("http://myserver/api/CustomerController", "application/json", HttpMethod.Get);
var apiCachedController = new ApiCachedController();
// Act
RequestManager.RegisterRequestWithThread();
var address = apiCachedController.GetClientIpAddress(request);
// Assert
Assert.AreEqual(address, "127.0.0.1");
}
In the Method CreateRequest you are referencing ApplicationInstance.Context on your baseContext Mock. However, you do not have a Setup on this Property:
var baseContextWrapper = new Mock(baseContext.Object.ApplicationInstance.Context);
Setup the Context on your Mock baseContext
I have a working OData controller, which supports all the normal get/put etc.
What I want to do is pass a normal odata $filter string from the client, parse and execute the filter on the server and run some code on the resulting IEnumerable.
I've messed around with ODataQueryContext, ODataQueryOptions, FilterQueryOption etc, but not really got anywhere.
Does anyone have any working examples?
Edit: I've added my function skeleton, just need to fill in the blanks
public HttpResponseMessage GetJobs(string filter)
{
*** How to convert the filter into IQueryable<Job> ***
var queryable = ?????
var settings = new ODataQuerySettings();
var jobs = queryOptions.ApplyTo(querable, settings) as IQueryable<Job>;
CsvSerializer csvSerializer = new CsvSerializer();
string csv = csvSerializer.Serialise(jobs);
string fileName = string.Format("{0} Jobs.csv", filter);
return CreateCsvResponseMessage(csv, fileName);
}
I recently had a scenario where I needed this sort of feature as well. This is what I came up with.
private static IQueryable<T> ApplyODataFilter<T>(IQueryable<T> data, string filterString) where T : class
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<T>(typeof(T).Name);
ODataQueryContext context = new ODataQueryContext(builder.GetEdmModel(), typeof(T), new ODataPath());
ODataQueryOptionParser queryOptionParser = new ODataQueryOptionParser(
context.Model,
context.ElementType,
context.NavigationSource,
new Dictionary<string, string> { { "$filter", filterString } });
FilterQueryOption filter = new FilterQueryOption(filterString, context, queryOptionParser);
IQueryable query2 = filter.ApplyTo(data, new ODataQuerySettings());
return query2.Cast<T>();
}
Try using OData code generator to generate client side code. you can following the following blog:
How to use OData Client Code Generator to generate client-side proxy class
The for the filter, the following is an example:
var q2 = TestClientContext.CreateQuery<Type>("Accounts").Where(acct => acct.Birthday > new DateTimeOffset(new DateTime(2013, 10, 1)));
There are some sample code in the codeplex to show how to do query.
Check this:
https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataQueryableSample/Program.cs
Update:
There is some sample code in the controller of the sample I gave you.
Write your code as below:
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
if (queryOptions.Filter != null)
{
var settings = new ODataQuerySettings();
var filterResult = queryOptions.ApplyTo(OrderList.AsQueryable(), settings) as IQueryable<Order>;
// Use the filter result here.
}
}
Update 2:
You can get the raw string of the filter from ODataQueryOptions.
public IQueryable<Order> Get(ODataQueryOptions queryOptions)
{
string filterString = queryOptions.Filter.RawValue;
// Use the filterString
}
Update 3:
(Note: ODataProperties is an extension method in static class
System.Web.Http.OData.Extensions.HttpRequestMessageExtensions)
public HttpResponseMessage GetJobs(string filter)
{
var context = new ODataQueryContext(Request.ODataProperties().Model, typeof(Job));
var filterQueryOption = new FilterQueryOption(filter, context);
IQueryable<Job> queryable = GetAllJobs();
var settings = new ODataQuerySettings();
var jobs = filterQueryOption.ApplyTo(queryable, settings) as IQueryable<Job>;
CsvSerializer csvSerializer = new CsvSerializer();
string csv = csvSerializer.Serialise(jobs);
string fileName = string.Format("{0} Jobs.csv", filter);
return CreateCsvResponseMessage(csv, fileName);
}
I have a list of URLs that I obtained by querying Google Analytics data. I want to run each of these URLs through the MVC pipeline to get the ActionResult. The action result contains the view model from which I can extract some important information.
Based on the extensibility of MVC, I thought this would be easy. I thought I could mock up a HttpRequest using the string URL and pass it through the routing and controller. My end point would be invoking the action method which would return the ActionResult. I'm finding bits and pieces of what I need, but a lot of the methods are protected within the various classes and the documentation on them is pretty sparse.
I somehow want to reach in to the ControllerActionInvoker and get the result of the call to the protected function InvokeActionMethod.
First of all, Darin's answer got me started, but there's a lot more detail to the final solution, so I'm adding a separate answer. This one is complex, so bear with me.
There are 4 steps to getting the ViewResult from a URL:
Mock the RequestContext via the routing system (Darin's answer got me started on this).
Uri uri = new Uri(MyStringUrl);
var request = new HttpRequest(null, uri.Scheme + "://" + uri.Authority + uri.AbsolutePath, string.IsNullOrWhiteSpace(uri.Query) ? null : uri.Query.Substring(1));
var response = new HttpResponse(new StringWriter());
var context = new HttpContext(request, response);
var contextBase = new HttpContextWrapper(context);
var routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(contextBase);
// We shouldn't have to do this, but the way we are mocking the request doesn't seem to pass the querystring data through to the route data.
foreach (string key in request.QueryString.Keys)
{
if (!routeData.Values.ContainsKey(key))
{
routeData.Values.Add(key, request.QueryString[key]);
}
}
var requestContext = new System.Web.Routing.RequestContext(contextBase, routeData);
Subclass your controller. Add a public method that allows you to call the protected Execute(RequestContext) method.
public void MyExecute(System.Web.Routing.RequestContext requestContext)
{
this.Execute(requestContext);
}
In the same subclassed controller, Add a public event that hooks in to the protected OnActionExecuted event. This allows you to reach in a grab the ViewResult via the ActionExecutedContext.
public delegate void MyActionExecutedHandler(ActionExecutedContext filterContext);
public event MyActionExecutedHandler MyActionExecuted;
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (MyActionExecuted != null)
{
MyActionExecuted(filterContext);
}
}
Tie everything together by instantiating an instance of the new controller subclass, adding an event handler, and calling the new public execute method (passing in the mocked RequestContext). The event handler will give you access to the ViewResult.
using (MyCompany.Controllers.MyController c = new Controllers.MyController())
{
c.MyActionExecuted += GrabActionResult;
try
{
c.MyExecute(requestContext);
}
catch (Exception)
{
// Handle an exception.
}
}
and here's the event handler:
private void GrabActionResult(System.Web.Mvc.ActionExecutedContext context)
{
if (context.Result.GetType() == typeof(ViewResult))
{
ViewResult result = context.Result as ViewResult;
}
else if (context.Result.GetType() == typeof(RedirectToRouteResult))
{
// Handle.
}
else if (context.Result.GetType() == typeof(HttpNotFoundResult))
{
// Handle.
}
else
{
// Handle.
}
}
The difficulty here consists into parsing the url into its constituent controller and action. Here's how this could be done:
var url = "http://example.com/Home/Index";
var request = new HttpRequest(null, url, "");
var response = new HttpResponse(new StringWriter.Null);
var context = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
var values = routeData.Values;
var controller = values["controller"];
var action = values["action"];
Now that you know the controller and the action you could use reflection to instantiate and execute it.
Try this:
object result = null;
Type controller = Type.GetType("MvcApplication4.Controllers.HomeController");
if (controller != null)
{
object controllerObj = Activator.CreateInstance(controller, null);
if (controller.GetMethod("ActionName") != null)
{
result = ((ViewResult)controller.GetMethod("ActionName").Invoke(controllerObj, null)).ViewData.Model;
}
}
I assumed normal routes are configured in the application and can be retrieved using regex or string operations. Following your discussion, I learned that you guys want to really follow through the MVC pipeline by digging into the framework by not using reflection or any hardcording techniques. However, I tried to search to minimize hardcoding by trying to match the url with the routes configured in the application by following this thread
How to determine if an arbitrary URL matches a defined route
Also, I came across other thread which creates httprequest to access routedata object but again reflection needs to be used for this.
String URL to RouteValueDictionary
Thanks Ben Mills, this got me started with my own problem. However I found that I didn't have to do 2, 3 or 4, by doing the following.
Uri uri = new Uri(MyStringUrl);
var absoluteUri = uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
var query = string.IsNullOrWhiteSpace(uri.Query) ? null : uri.Query.Substring(1);
var request = new HttpRequest(null, absoluteUri, query);
Getting access to the string writer is important.
var sw = new StringWriter();
var response = new HttpResponse(sw);
var context = new HttpContext(request, response);
var contextBase = new HttpContextWrapper(context);
var routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(contextBase);
If we assign the RouteData to the request context we can use the MVC pipeline as intended.
request.RequestContext.RouteData = routeData;
var controllerName = routeData.GetRequiredString("controller");
var factory = ControllerBuilder.Current.GetControllerFactory();
var contoller = factory.CreateController(request.RequestContext, controllerName);
controller.Execute(request.RequestContext);
var viewResult = sw.ToString(); // this is our view result.
factory.ReleaseController(controller);
sw.Dispose();
I hope this helps someone else wanting to achieve similar things.
I have an MVC 4 Web API. Usually I want responses to return all properties, but there is one place I only want to return only non-null values. I can setup either behavior by setting the JsonSerializerSettings of the Formatters.JsonFormatter.SerializerSettings.NullValueHandling of the GlobalConfiguration.Configuration instance in the global file but I want to use both depending on the response. Is there an easy way to configure the request scope from within an API controller action?
By changing your controller action to return HttpResponseMessage you can get more control over how your content is returned for a particular action. e.g.
public HttpResponseMessage Get() {
var foo = new Foo();
var objectContent = new ObjectContent<Foo>(foo, new JsonFormatter()
{SerializerSettings.NullValueHandling = ???})
return new HttpResponseMessage() {Content = objectContent};
}
this would probably be easier to do on the client side with a dynamic language like javascript.
var keys = Object.keys(json);
for(var i = 0; i < keys.length; i++) {
var propertyName = keys[i];
if(json[propertyName] === undefined || v[propertyName] === null) {
json.remove(propertyName);
}
}
return json;
I'm building a website in MVC 4 & using Automapper to map from domain objects to Viewmodel objects. I have injected Automapper as stated here http://rical.blogspot.in/2012/06/mocking-automapper-in-unit-testing.html
and it's working fine inside action methods while debugging, but during unit testing the action method when I inject automapper service I find that service.map is returning null. But while debugging the mapping is fine. I'm not being able to find the reason, trying for over 4 hrs. I have a domain class called Interview & its corrosponding viewmodel as InterviewModel. I have initialized mapping as CreateMap(); in automapper profile config, that has been called from global startup method. Below is the controller & action...
public class NewsAndViewsController : Controller
{
private IInterviewRepository repository;
private IMappingService mappingService;
public NewsAndViewsController(IInterviewRepository productRepository, IMappingService autoMapperMappingService)
{
repository = productRepository;
mappingService = autoMapperMappingService;
}
[HttpPost, ValidateAntiForgeryToken]
[UserId]
public ActionResult Edit(InterviewModel interView, string userId)
{
if (ModelState.IsValid)
{
var interView1 = mappingService.Map<InterviewModel, Interview>(interView);
**// THE ABOVE LINE RETURNING NULL WHILE RUNNING THE BELOW TEST, BUT NOT DURING DEBUGGING**
repository.SaveInterview(interView1);
TempData["message"] = string.Format("{0} has been saved", interView.Interviewee);
return RedirectToAction("Create");
}
return View(interView);
}
}
[TestMethod]
public void AddInterview()
{
// Arrange
var interviewRepository = new Mock<IInterviewRepository>();
var mappingService = new Mock<IMappingService>();
var im = new InterviewModel { Interviewee="sanjay", Interviewer="sanjay", Content="abc" };
mappingService.Setup(m => m.Map<Interview, InterviewModel>(It.IsAny<Interview>())).Returns(im);
var controller = new NewsAndViewsController(interviewRepository.Object, mappingService.Object);
// Act
var result = controller.Edit(im, "2") as ViewResult;
// Assert - check the method result type
Assert.IsNotInstanceOfType(result, typeof(ViewResult));
}
In your test you've got your Interview and InterviewModel classes crossed up in the mappingService.Setup() call (as an aside, I think you could use better naming conventions, or don't use var, to keep your objects clear - "im", "interview" and "interview1" don't make it easy to follow which is the model and which is the view object).
Try this:
[TestMethod]
public void AddInterview()
{
// Arrange
var interviewRepository = new Mock<IInterviewRepository>();
var mappingService = new Mock<IMappingService>();
var interview = new Interview();
var im = new InterviewModel { Interviewee="sanjay", Interviewer="sanjay", Content="abc" };
mappingService.Setup(m => m.Map<InterviewModel, Interview>(im).Returns(interview);
var controller = new NewsAndViewsController(interviewRepository.Object, mappingService.Object);
// Act
var result = controller.Edit(im, "2") as ViewResult;
// Assert - check the method result type
Assert.IsNotInstanceOfType(result, typeof(ViewResult));
}