Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Unit tests: run initialization code before each test

I'm using Visual Studio's Test Tools for unit testing. I need some initialization code to run before each test.

I have a Setup class for the initialization code. I already added code to run before each test run, using [AssemblyInitialize], but I can't figure out how to do the same on a single test basis.

I tried using the [TestInitialize] attribute, but this only applies to tests in the same file as the [TestInitialize] method. I would like the initialization code to run automatically for all tests in the assembly, without having to explicitly call it in each and every test file.

[TestClass]
public class Setup
{
    [AssemblyInitialize]
    public static void InitializeTestRun(TestContext context)
    {
        //... code that runs before each test run
    }

    [TestInitialize] //this doesn't work!
    public static void InitializeTest()
    {
        //... code that runs before each test
    }
}
like image 959
fikkatra Avatar asked Jun 16 '16 14:06

fikkatra


People also ask

Should you write unit tests before code?

It often makes sense to write the test first and then write as much code as needed to allow the test to pass. Doing this moves towards a practice known as Test-Driven Development (TDD). Bluefruit uses a lot of TDD because it helps us to build the right product without waste and redundancies.

Does TestInitialize run for each test?

TestInitialize and TestCleanup are ran before and after each test, this is to ensure that no tests are coupled. If you want to run methods before and after ALL tests, decorate relevant methods with the ClassInitialize and ClassCleanup attributes. Save this answer.

Should I run unit tests before build?

Always build the project(s) before running/debugging unit tests. Positive: always correct results, not confusing for users. in our case) even in case there were no changes at all. project(s).

What is the purpose of running a test before you develop the code?

It will allow you to write less code You only have to write enough code to pass the test. Once it passes, you're finished with that part. When you're trying to implement a large feature, it's easy to get lost in the code. Testing keeps you on track and focused when you are writing the code for that large feature.


2 Answers

The following should work (at least it works with other test frameworks):

  • Create a base class DatabaseIntegrationTests with the TestInitialize method
  • Derive your other Testclasses from that base class
like image 148
tobsen Avatar answered Sep 28 '22 08:09

tobsen


It is [TestInitialize] but you have the syntax wrong, it doesn't take a context:

[TestInitialize]
public static void InitializeTests()
{
    //... code that runs before each test
}
like image 33
stuartd Avatar answered Sep 28 '22 10:09

stuartd