AutoFixture to test MVC [duplicate] - unit-testing

This question already has an answer here:
AutoFixture fails to CreateAnonymous MVC Controller
(1 answer)
Closed 6 years ago.
Can anybody realize what I am missing here? I just want to create a controller to test. TController is a type argument of my TestFixture class. This code returns a NotImplementedException. Why?
var fixture = new Fixture().Customize(new AutoMoqCustomization());
SutController = fixture.Create<TController>();

I do not know why but I have to do the following:
var fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.Customize<ControllerContext>(c => c.OmitAutoProperties());
SutController = fixture.Create<TController>();

Related

Change JSON serialization from camelCase to PascalCase [duplicate]

This question already has answers here:
JSON serializer Not Working After Upgrade To 3.6.2
(2 answers)
Closed 3 years ago.
After migrating my project from Core 2.1. to 2.2. I am having trouble with my Kendo widgets. Fields in the model are specified with PascalCase and the field names returned from the server in the JSON are using camelCase.
I've added DefaultContractResolver in Startup but JSON is still serialized in camelCase. Any workaround here?
services
.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
We had a similar problem with Syncfusion expecting PascalCase.
Until now the only solution we found is to create our own
PascalCasePropertyNamesContractResolver : DefaultContractResolver
Therein we just override the ResolvePropertyName to return the key as is.
Unfortunately we have to reference this ContractResolver in each Json-Return, like this:
return Json(new { result = result.Items, count = result.Count }, new JsonSerializerSettings { ContractResolver = new PascalCasePropertyNamesContractResolver () });
If there are better solutions coming up here: welcome and thanks in advance.

Unit Test IActionResult with TempData [duplicate]

This question already has an answer here:
Mocking a TempData in ASP.NET Core in MSTest
(1 answer)
Closed 4 years ago.
I was just wondering how can you do unit testing with TempData without using MOQ or doing anything complex? Really appreciate your help
Here is my code:
public IActionResult ProjectsList(string selectedOrg)
{
TempData["model"] = selectedOrg;
return View("Index");
}
TempData is public property of controller, you can assert that expected key-value pair is in the bucket.
var controller = new MyController();
var expectedModel = "My organisation";
controller.ProjectsList(expectedModel);
controller.TempData.Should().Contain("model", expectedModel);

NUnit Test Fails due to a Null element in BaseController [duplicate]

I'm trying to test some application logic that is dependent on the Values property in ControllerContext.RouteData.
So far I have
// Arrange
var httpContextMock = new Mock<HttpContextBase>(MockBehavior.Loose);
var controllerMock = new Mock<ControllerBase>(MockBehavior.Loose);
var routeDataMock = new Mock<RouteData>();
var wantedRouteValues = new Dictionary<string, string>();
wantedRouteValues.Add("key1", "value1");
var routeValues = new RouteValueDictionary(wantedRouteValues);
routeDataMock.SetupGet(r => r.Values).Returns(routeValues); <=== Fails here
var controllerContext = new ControllerContext(httpContextMock.Object, routeDataMock.Object, controllerMock.Object);
The unit test fails with:
System.ArgumentException: Invalid setup on a non-overridable member:
r => r.Values
Creating a fake RouteData doesn't work either as the constructor is RouteData(RouteBase,IRouteHandler).
The important class here is the abstract class RouteBase which has the method GetRouteData(HttpContextBase) which returns an instance of RouteData, the class I'm trying to fake. Taking me around in circles!
Any help on this would be most welcome.
RouteData also has a constructor that takes no arguments. Simply create one and add the values to it that you want. No need to mock it when you can create one.
var routeData = new RouteData();
routeData.Values.Add( "key1", "value1" );
var controllerContext = new ControllerContext(httpContextMock.Object, routeData, controllerMock.Object);
I'm very new to TDD in conjunction with mock objects, but a lesson I learned early on from a colleague was not to mock types you don't own. Thus, don't try to mock RouteData. The idea was originally conceived by Joe Walnes (though I can't find where he said it).

webapi: unittest ActionFilterAttribute OnActionExecutingAsync with moq

Edit: Why doesn't Moq run the overridden ToString method? gives the hint. I had to set filtermock.CallBase to true. Now it works.
I'm trying to write a unittest for an asp.net webapi project. What I want to do is, to test a function with its corresponding filter. I setup the controller and the filter moq objects like this:
var filtermock= new Mock<MyActionFilterAttribute>();
filtermock.SetupGet(attr => attr.UserId).Returns(userName);
[...]
var controllermock = new Mock<MyController>();
var filtermock = new Mock<MyActionFilterAttribute>();
The unittest looks like this:
var controller = controllermock.Object;
var filter = filtermock.Object;
await filter.OnActionExecutingAsync(null, CancellationToken.None);
await controller.MyTestFunction();
await filter.OnActionExecutedAsync(null, CancellationToken.None);
The problem is, that the overridden functions OnActionExecutingAsync and OnActionExecudedAsync are not beeing called when i run/debug the test. I guess the baseclasses of ActionFilterAttribute are called? Could anyone give me a hint what I am doing wrong here?
How do you expect filtermock to ever be called? It does not appear the filtermock is associated to the controllermock so the controllermock is not even aware of the filtermock.
This is the same issue I am trying to resolve myself: how to inject an action filter into a controller.

MVC-Unit test - ViewEngines

Hey,
I'm working with mvc I have to write unit test for function that contains
var result = ViewEngines.Engines.FindPartialView(context, partialPath);
and my test fails on this part : "The RouteData must contain an item named 'controller' with a non-empty string value."How can I make face object for this?
thx
add that for controller
var routeData = new RouteData();
routeData.Values.Add("controller", "someName");
routeData.Values.Add("action", "someAction");