Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Unit Test This Simple Form

I'm trying to understand writing unit tests for simple scenarios, and can't find anything that gets this simple. Let's say I have a web form with the following two form fields:

FirstName
LastName

on the backend, I have this class:

class User
{
   public string FirstName {get;set;}
   public string LastName {get;set}
}

that these form fields map to and then I save to the database with plain old ADO.NET (no frameworks). I have no validation, it just saves it via an INSERT statement.

Where does unit testing fit in? What unit test do I write? Is this even worth testing? If I DID have validation functions, then I could test those, right?

Thanks.

like image 856
SaltProgrammer Avatar asked Feb 18 '26 21:02

SaltProgrammer


1 Answers

You don't really unit-test forms and UIs. What you'd do is split your UI into two parts: the HTML that is rendered and returned to the client, and the server-side part. This is really part of Integration testing, not unit testing. Note that despite it not being a unit test, you can still fully-automate integration tests (it just means that unit testing frameworks like NUnit aren't really appropriate and you'll need to make your own tools).

You can test the client-side part by getting the HTML and running it through a HTML analyser, like HtmlAgilityPack, and ensuring that all of the URIs in the page return 200 and that all form fields are present with the correct name="" attributes.

You'd then test the server-side part separately, by having a program that submits POST form requests with sample data, and then which inspects your database directly and ensures that the newly-submitted data is now in the database in the correct format. You'd use a dedicated testing database for this as running test tools against a production database is never a good idea.

I cannot tell you if it's worth writing automated tests for your application - it can often take as much time as, if not more than, writing the application code. You do it to ensure correctness which matters in safety-critical or mission-critical systems. The simple question to ask is "if my program is incorrect, will people die/get hurt or will people lose money?", if the answer is "yes" then you should do it.

Tests like these can also be used in running applications to monitor "application health". For example, one application system I wrote interfaces with the public telephone system, so I needed to write a tester that ensures that the application is successfully making telephone calls).

like image 120
Dai Avatar answered Feb 20 '26 10:02

Dai