LittleBachman LittleBachman - 1 month ago 7
C# Question

Do I need to unit test this function?

I've been researching a lot about unit testing and I have a couple functions whose only purpose is to add or update rows in a database based on user input from the model. From what I've read, it doesn't seem like unit testing is really used for that. An integration test might make more sense but I haven't researched those as much yet. I'm sorry if this is covered elsewhere, I tried to find a similar example and this questions is the closest I could find: ...which implies that a unit test is not the best way to test a function that just calls the database.

Here's an example of one of our db functions...

public void AddDependant(AddDependantView addDependantView, int ID)
using (var db = new EnrollmentDataModel())
Dependant dependant = new dependant();
dependant.ID = ID;
dependant.FirstName = addDependantView.FirstName;
dependant.LastName = addDependantView.LastName;
dependant.Relation = addDependantView.Relation;
dependant.Birthday = (addDependantView.BirthDate).Value.ToString("MM/dd/yyyy");
dependant.Active = true;
dependant.RowCreatedDateTime = DateTime.Now;


UpdateLog(ID, "Dependant Data Added", "User added their dependant data.");

The "UpdateLog" function called at the end is similar in structure to this one but adds an entry in a different database that logs any user activity.

So would this function benefit from unit testing? If it does what would be the benefit? Would an integration test be a better alternative? I'm sorry if this is too basic or too broad but I'm pretty new to unit testing and want to get into good practices.


To answer your question at the end, this function would benefit more from an integration test. The benefit you'd get form unit testing this function is mainly just a notification when something in your code changes.

For example, with mocks/spies/stubs you could write tests to assert that this functions makes the correct db api calls. And that those calls get the correct arguments. However those tests could pass as unit tests and still fail in integration tests if your mocks get out of sync with the real thing.

The best part you could unit test here is that dependent object. Assert that it has an ID, FirstName, LastName, etc... Then if your production code ever changed, say one of those properties was accidentally deleted. Your unit test would let you know much faster than your integration tests could.

The downside to that is that you're more likely to change something on purpose then on accident. These Unit Tests could become annoying since they fail every-time you change something.

So there's the benefit and the downside. Whether the benefit is worth the trouble is up to you. I think most would agree though that for something like this function, an integration test is all you really need.