Unit Test IActionResult with TempData [duplicate] - unit-testing

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);

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.

AutoFixture to test MVC [duplicate]

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>();

How to use F# to unit test C# logic [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I am learning F# on my own and am trying to sneak some F# into the workplace.
As a result, I would like to write unit tests in F# to test C# logic.
Can anyone provide me a simple example of an F# unit test targeting a C# method and verifying a C# property as a result of exercising that method?
UPDATE:
Here's an example. When a value is provided for first and last name, how do we unit test (in F#) that GetFullName returns first and last name?
namespace MVVMExample
{
public class ViewModel : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
RaisePropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
RaisePropertyChanged("LastName");
}
}
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
So a very simple test for this ViewModel using NUnit could look like this:
testing GetFullName
here is a possible test for this function:
[<Test>]
member __.``GetFullName = "Jon Doe" if FirstName = "Jon" and LastName = "Doh"``() =
let vm = ViewModel()
vm.FirstName <- "Jon"
vm.LastName <- "Doe"
Assert.AreEqual("Jon Doe", vm.GetFullName())
testing PropertyChanged
[<TestFixture>]
type ``ViewModel Unit Tests``() =
[<Test>]
member __.``a PropertyChanged event should be raised if the FirstName was changed``() =
let vm = ViewModel()
let mutable lastChangedProperty = ""
vm.PropertyChanged.Add (fun e -> lastChangedProperty <- e.PropertyName)
vm.FirstName <- "Tom"
Assert.AreEqual("FirstName", lastChangedProperty)
Of course this is not really functional but I think it should be reasonable clear for the given problem.
as you can see it's basically the same you would expect from a C# test - the only F# feature I used are the function/class names in ``...`` which makes the output in your test-runner look nicer:
Code Walkthrough
the [TestFixture] class Test {...} just translates into [<TestFixture>] type Test() = ...
a [Test] method is just [<Test>] member this.MyTestFunction() = ... (this only if you need it - as you can see I did not so I used the idiomatic I-don't-care __ placeholder - see in F# you can name your this-reference any way you want - and you have to do it on each class-member.
as I want to change the lastChangedProperty string if the event is fired I declared it mutable (so you can use the assign operator <-)
to add an event-handler you can just use the .Addfunction on the event
(fun e -> ..) is an lambda - in C# this would be e => ...
disclaimer
of course if you want to use this viewmodel in say a WPF application you should make sure to dispatch to the UI-Thread, etc. which would make the test more nasty but for your example a simple red-green cycle should work ;)
I hope this helps you out (but of course it does not really show the advantages of F# as the test here is ugly side-effecty)

how can I write unit test to my meteor methods?

I found it a little complicated, and more complicated if I wrote my meteor methods in /lib folder, that I want is to test from server test folder my methods (unit test), but stub this.userId and also debugging or showing logs in server side does not help too much.
I was having too much problems with it, I'm using mochajs with velocity, does anyone would help me please? is someone know how can I write the units to meteor methods?
Mocha doesn't support unit tests, only Jasmine does currently. This is an example of how you would write a unit test in Jasmine for the server and use userId.
it("should return premium content to logged in users", function () {
// SETUP
var thisContext = {
userId : true
};
var expectedCursor = 'chapter_cursor1';
var _query = true, _modifiers = true;
Chapters.find = function(query, modifiers) {
_query = query;
_modifiers = modifiers;
return expectedCursor;
};
// EXECUTE
var actualCursor = Meteor.publishFunctions['chapters'].apply(thisContext);
// VERIFY
expect(actualCursor).toBe(expectedCursor);
expect(_query).toBe(undefined);
expect(_modifiers).toBe(undefined);
});
Taken from here: https://github.com/xolvio/Letterpress/blob/master/tests/jasmine/server/unit/chaptersSpec.js#L3

Unit Testing in ASP.NET MVC: Minimising the number of asserts per test

I'm trying out TDD on a greenfield hobby app in ASP.NET MVC, and have started to get test methods such as the following:
[Test]
public void Index_GetRequest_ShouldReturnPopulatedIndexViewModel()
{
var controller = new EmployeeController();
controller.EmployeeService = GetPrePopulatedEmployeeService();
var actionResult = (ViewResult)controller.Index();
var employeeIndexViewModel = (EmployeeIndexViewModel)actionResult.ViewData.Model;
EmployeeDetailsViewModel employeeViewModel = employeeIndexViewModel.Items[0];
Assert.AreEqual(1, employeeViewModel.ID);
Assert.AreEqual("Neil Barnwell", employeeViewModel.Name);
Assert.AreEqual("ABC123", employeeViewModel.PayrollNumber);
}
Now I'm aware that ideally tests will only have one Assert.xxx() call, but does that mean I should refactor the above to separate tests with names such as:
Index_GetRequest_ShouldReturnPopulatedIndexViewModelWithCorrectID
Index_GetRequest_ShouldReturnPopulatedIndexViewModelWithCorrectName
Index_GetRequest_ShouldReturnPopulatedIndexViewModelWithCorrectPayrollNumber
...where the majority of the test is duplicated code (which therefore is being tested more than once and violates the "keep tests fast" advice)? That seems to be taking it to the extreme to me, so if I'm right as I am, what is the real-world meaning of the "one assert per test" advice?
It seems just as extreme to me, which is why I a also write multiple asserts per test. I already have >500 tests, writing just one assert per test would blow this up to at least 2500 and my tests would take over 10 minutes to run.
Since a good rest runner (such as Resharper's) lets you see the line where the test failed very quickly, you should still be able to figure out why a test failed with little effort. If you don't mind the extra effort, you can also add an assert description ("asserting payroll number correct"), so that you can even see this without even looking at the source code. With that, there is very little reason left to just one assert per test.
In his book The Art of Unit Testing, Roy Osherove talks about this subject. He too is in favour of testing only one fact in a unit test, but he makes the point that that doesn't always mean only one assertion. In this case, you are testing that given a GetRequest, the Index method ShouldReturnPopulatedIndexViewModel. It seems to me that a populated view model should contain an ID, a Name, and a PayrollNumber so asserting on all of these things in this test is perfectly sensible.
However, if you really want to split out the assertions (say for example if you are testing various aspects which require similar setup but are not logically the same thing), then you could do it like this without too much effort:
[Test]
public void Index_GetRequest_ShouldReturnPopulatedIndexViewModel()
{
var employeeDetailsViewModel = SetupFor_Index_GetRequest();
Assert.AreEqual(1, employeeDetailsViewModel.ID);
}
[Test]
public void Index_GetRequest_ShouldReturnPopulatedIndexViewModel()
{
var employeeDetailsViewModel = SetupFor_Index_GetRequest();
Assert.AreEqual("Neil Barnwell", employeeDetailsViewModel.Name);
}
[Test]
public void Index_GetRequest_ShouldReturnPopulatedIndexViewModel()
{
var employeeDetailsViewModel = SetupFor_Index_GetRequest();
Assert.AreEqual("ABC123", employeeDetailsViewModel.PayrollNumber);
}
private EmployeeDetailsViewModel SetupFor_Index_GetRequest()
{
var controller = new EmployeeController();
controller.EmployeeService = GetPrePopulatedEmployeeService();
var actionResult = (ViewResult)controller.Index();
var employeeIndexViewModel = (EmployeeIndexViewModel)actionResult.ViewData.Model;
var employeeDetailsViewModel = employeeIndexViewModel.Items[0];
return employeeDetailsViewModel;
}
It could also be argued that since these tests require the same setup, they should get their own fixture and have a single [SetUp] method. There's a downside to that approach though. It can lead to lots more unit test classes than actual, real classes which might be undesirable.
I use a helper class to contain the asserts. This keeps the test methods tidy and focused on what they're actually trying to establish. It looks something like:
public static class MvcAssert
{
public static void IsViewResult(ActionResult actionResult)
{
Assert.IsInstanceOfType<ViewResult>(actionResult);
}
public static void IsViewResult<TModel>(ActionResult actionResult, TModel model)
{
Assert.IsInstanceOfType<ViewResult>(actionResult);
Assert.AreSame(model, ((ViewResult) actionResult).ViewData.Model);
}
public static void IsViewResult<TModel>(ActionResult actionResult, Func<TModel, bool> modelValidator)
where TModel : class
{
Assert.IsInstanceOfType<ViewResult>(actionResult);
Assert.IsTrue(modelValidator(((ViewResult) actionResult).ViewData.Model as TModel));
}
public static void IsRedirectToRouteResult(ActionResult actionResult, string action)
{
var redirectToRouteResult = actionResult as RedirectToRouteResult;
Assert.IsNotNull(redirectToRouteResult);
Assert.AreEqual(action, redirectToRouteResult.RouteValues["action"]);
}
}