I've written a back-end in C# with simple HTTP methods. Get, Post (create), Put (update), Delete.
Now I want to implement some unit tests with NUnit. I've found this article where the basics of NUnit are described. But now the question is, how do I use this to create the unit tests?
Can anybody explain what I have to do to test the controllers HTTP methods?
Thanks in advance :)
EDIT:
To make things clear, I want to test if its possible to get, create, update, delete items over my controller class.
Assuming you are using ASP.NET MVC, you can do something like this:
public class ProductController : Controller
{
public ActionResult Index()
{
// Add action logic here
throw new NotImplementedException();
}
public ActionResult Details(int Id)
{
return View("Details");
}
}
[TestFixture]
public class ProductControllerTest
{
[Test]
public void TestDetailsView()
{
var controller = new ProductController();
var result = controller.Details(2) as ViewResult;
Assert.AreEqual("Details", result.ViewName);
}
}
Example taken from https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs
Personally I tend to avoid putting much logic in the controllers themselves, as they are not that simple to test (as you can now see).
Rather, add a service layer which does any required business logic and test THAT. that way the logic can be re-used in non-MVC situations too.
this way, your controller action can be reduced to something like:
//Controller action
IHttpResult DoSomething(string input)
{
var model = SomeService.DoThings(input);
return View("~/views/DoSomethingView.cshtml", model);
}
Which is so light that you can probably manage to sleep at night without needing to unit test it really, but SomeService can be completely unit tested easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With