1598652000
Based on Betteridge’s law of headlines: no!
But based on recent twitter activity, that’s no doubt a somewhat controversial opinion, so in this post I look at what a unit-test for an API controller might look like, what a unit-test is trying to achieve, and why I think integration tests in ASP.NET Core give you far more bang-for-your-buck.
I start by presenting my thesis, about why I don’t find unit tests of controllers very useful, acknowledging the various ways controllers are used in ASP.NET Core. I’ll then present a very simple (but representative) example of an API controller, and discuss the unit tests you might write for that class, the complexities of doing so, as well as the things you lose by testing the controller outside the ASP.NET Core MVC framework as a whole.
This post is not trying to suggest that unit tests are bad in general, or that you should always use integration tests. I’m only talking about API/MVC controllers here.
The MVC/API controllers people write generally fall somewhere on a spectrum:
DbContext
, or IService
is injected and manipulated in the action method body:public class BlogPostController : Controller
{
// Often this would actually be an EF Core DB Context injected in constructor!
private readonly IRepository _repository;
public BlogPostController(IRepository repository) => _repository = repository;
[HttpPost]
public ActionResult<Post> Create(InputModel input)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Some "business logic"
if(_repository.IsSlugAvailable(input.Slug)
{
ModelState.AddError("Slug", "Slug is already in use");
return BadRequest(ModelState);
}
var model = new BlogPost
{
Id = model.Id,
Name = model.Name,
Body = model.Body,
Slug = model.Slug
});
_repository.Add(model);
return result;
}
}
public class BlogPostController : BaseApiController
{
[HttpPost]
public async Task<IActionResult> Create([FromBody]NewPostCommand command)
{
var result = await Mediator.Send(command);
return Ok(result);
}
}
So which approach do I use? Well, as always it depends. In general, I think the second option is clearly the more scalable, manageable, and testable option, especially when used in conjunction with conventions or libraries that enforce that practice.
But sometimes, I write the other types of controllers. Sometimes it’s because I’m being sloppy. Sometimes it’s because I need to do some HTTP related manipulation which wouldn’t make sense to do in a command handler. Sometimes the action is so simple it just doesn’t warrant the extra level of indirection.
What I don’t do (any more 🤦♂️), is put important domain logic in action methods. Why? Because it makes it harder to test.
“But you can unit-test controllers!” I hear you cry. Well…yes…but…
MVC/API controllers are classes, and actions are just methods, so you can create and invoke them in unit tests the same way you would any other system under test (SUT).
The trouble is, in practice, controllers do most of their useful work as part of a framework, not in isolation. In unit tests, you (intentionally) don’t get any of that.
In this section I highlight some of the aspects of MVC controllers that you can’t easily test or wouldn’t want to test in a unit test.
#asp.net core #testing #mvc
1602560783
In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.
To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.
Sub-topics discussed :
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From new project window, Select Asp.Net Core Web Application_._
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.
Now let’s define DB model class file – /Models/TransactionModel.cs.
public class TransactionModel
{
[Key]
public int TransactionId { get; set; }
[Column(TypeName ="nvarchar(12)")]
[DisplayName("Account Number")]
[Required(ErrorMessage ="This Field is required.")]
[MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
public string AccountNumber { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Beneficiary Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BeneficiaryName { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Bank Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BankName { get; set; }
[Column(TypeName ="nvarchar(11)")]
[DisplayName("SWIFT Code")]
[Required(ErrorMessage = "This Field is required.")]
[MaxLength(11)]
public string SWIFTCode { get; set; }
[DisplayName("Amount")]
[Required(ErrorMessage = "This Field is required.")]
public int Amount { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
}
C#Copy
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContextclass for EF Core.
#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup
1602564619
User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.
Sub-topics discussed :
ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.
ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.
The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.
First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.
Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.
#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core
1582912113
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1582896228
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1582881342
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework