Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An example of unit testing in C#?

What exactly is a unit test and how do I write one? I hear many times people write them before their app is even written, how can this be? I am under the impression that a unit test is some code that makes a call to a method of your app with a set value and expects a specific value to come back, if the specific value does not come back the test has failed. Am I wrong or mislead here? I read so much about unit testing but I know very little about what it actually looks like in code so a sample would be great.

Is this a unit test?

start psuedo code...

CheckForDuplicateSubdomains(){
  get all users in DB with matching subdomains
  if greater than zero, fail test
}

PS: I am using ASP.NET MVC in C#

like image 669
MetaGuru Avatar asked Feb 04 '23 08:02

MetaGuru


2 Answers

You are correct about unit testing. The idea is to test all your functions, one by one, with different inputs to make sure they work like you expect (as opposed to finding out after they've been inserted into an application.. and then making the testing more complicated).

Writing the unit tests before you write the function is part of a methodology called "Test driven development". In which you write the skeleton of the function only, and all the unit tests first. So at first all your tests will fail (b/c the function is not programmed yet). After that you program the function until all the tests pass.

like image 166
Nestor Avatar answered Feb 11 '23 22:02

Nestor


Yes, your example would be a unit test. There are a few reasons to create the test first. First, it acts as living documentation for your project. It establishes behaviors and expected outcomes, which should help you actually implement your code (it's easier to write something, knowing what it needs to do and basically how it is initiated). Secondly, if you write the test afterward, you're more likely to write a test that works with the code you already wrote, which doesn't help you. Define what a unit of code needs to do, write the tests, and write/fix the code so it reflects the behaviors in the tests. This strategy translates into improved understanding and quality as your application evolves.

like image 42
moribvndvs Avatar answered Feb 11 '23 23:02

moribvndvs