TagUnit tests

Parameterizing Unit Tests using xUnit

xUnit allows our unit test to use parameters, which allows us to test our code for multiple scenarios without needing to write multiple methods with same content.

Let’s look at example from previous lesson

Here we test if 3 + 9 equals 12.

But what if we wanted to test our Add method for multiple scenarios?

 

We could use InlineData Attribute.

InlineData Attribute allows us to run our test with input parameters, and passes those parameters to test method using params object[] data.

We are not done yet.

Compiler is not happy and we are getting error : Fact methods cannot have parameters.

Simple solution is to replace Fact Attribute with Theory Attribute

Now, when we run our unit test we can see that same test method ran 3 times an all test have passed  🙂

Also note that we can also see input parameters!

How to create Unit Test with VisualStudio 2017

This brief tutorial will show you how to create Unit Test with VisualStudio 2017.

There are a few ways to create unit test using VS 2017.

1) Create unit test From the class

Create new Console Application

And in a Program class add public method.

Right click on a method and chose “Create Unit Tests”.

How to add an Unit test project from a class.

 

 

 

 

 

 

Be sure to add a public method because without it you will get an error:

Create Unit Tests is supported only within a public class or a public method

An error is pretty straight forward 🙂

"Create Unit Tests is supported only within a public class or a public method" error.

Error you get when adding Unit test project from an empty class or class that has only static members.

 

 

 

 

Then you can chose additional options or additional Testing frameworks

Unit test options

 

 

 

 

 

2) Manually adding a test project

Create new method that returns string with value test.

Right click solution and add Unit Testing project

Choosing unit test project

 

 

 

 

 

 

Then add an reference to project you wish to unit test

And create a new class ProgramTests

Decorate class with a [TestClass] Attribute

Also add a ShouldReturnTestString void method decorated with a [TestMethod] Attribute

Be sure to add those Attributes because without them you will not be able to run unit test. Give it a shot.

© 2021 LearnC#WithDarko

Theme by Anders NorenUp ↑