Most examples I see of Unit tests are simple tests like Assert.That(5, 2 + 3), but how would I incorporate a unit test a method that gets a users information and saves them to a database. For example, I have a Register method that takes a User object. The User object properties are populated from a web form and then it is saved to the database. What are some viable unit tests that I could do with this?
Here is an example. Assume that the User object has some required fields such as Email, FirstName, LastName. Would a valid unit test assert that Email is not null or empty. The same applies to other required fields. So in my scenario above, would this be a unit test.
[Test]
public void EmptyEmailShouldReturnError()
{
User user = new User();
user.Email = "";
//Set other properties
//Not sure of nunit syntax here, so I will make something up.
Assert.IsNotEmpty(user.Email);
}
Those are not unit tests. Unit test are for testing things in isolation. Things that interact directly with a database cannot be tested in isolation as they depend on this database. If you want to test things in isolation you need to introduce levels of abstractions to avoid the strong coupling between your components. In a unit-test a common technique is to replace some component with a mocked object. This is possible only if you have abstracted your database access layer for example.
Now back to the question. How do you test your database access layer? Those are called integration tests. There are many techniques for performing integration tests with a database. Some of them consist of having a test database which is recreated in the Setup method and dropped in the TearDown method, so that all the tests assume some valid state to work with. So you might have some scripts that create and fill the database with test data and those scripts are called before running each test. You could even wrap everything inside a database transaction which will be rolled back at the end.