Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test C# [TestInitialize]

I am performing Unit Tests on C# Web API controllers - and each one requires several parameters to initialize. I have the following code in each test at the moment but it's very bulky. How can I put this code into the [TestInitialize] so that it runs before each test?

I have tried the following but obviously it exists out of scope for the testmethods.

[TestInitialize]
public void TestInitialize()
{
    APIContext apicon = new APIContext();
    xRepository xRep = new xRepository(apicon);
    var controller = new relevantController(cRep);
    controller.Request = new HttpRequestMessage();
    controller.Configuration = new HttpConfiguration();
    relevantFactoryModel update = new relevantFactoryModel();
}   
like image 660
anthonyhumphreys Avatar asked Oct 24 '14 12:10

anthonyhumphreys


People also ask

What is a unit test in C?

A Unit Testing Framework for C CUnit is a lightweight system for writing, administering, and running unit tests in C. It provides C programmers a basic testing functionality with a flexible variety of user interfaces. CUnit is built as a static library which is linked with the user's testing code.

Does C have unit testing?

One unit testing framework in C is Check; a list of unit testing frameworks in C can be found here and is reproduced below. Depending on how many standard library functions your runtime has, you may or not be able to use one of those.

What is test function C?

The test() function in C++ is used to test whether in a bit string at the specified index the bit is set or not. The test() function is a built-in function in C++ which is defined in the <bits/stdc++. h> or <bitset> header file, this header file includes every standard library.


1 Answers

You can set the variables that you need as fields of the test class and then initialize them in the TestInitialize method.

class Tests 
{
    // these are needed on every test
    APIContext apicon;
    XRepository xRep;
    Controller controller;
    RelevantFactoryModel update;

    [TestInitialize]
    public void TestInitialize()
    {
        apicon = new APIContext();
        xRep = new xRepository(apicon);
        controller = new relevantController(cRep);
        controller.Request = new HttpRequestMessage();
        controller.Configuration = new HttpConfiguration();
        update = new relevantFactoryModel();
    }   
}

This way the fields can be accessed from every test

like image 59
dmorganb Avatar answered Oct 19 '22 23:10

dmorganb