简体   繁体   中英

Easy valid way of unit testing C++ code you can't work out on paper

I am trying to test some C++ code, using Visual Studio 2015's built in unit test framework. I have written some code which is testing an hourly, daily & weekly model, to see which one most reliably fits a set of real life data, by calculating the Coefficient of Determination (R^2).

The real life data needs to be "Read" off of a graph, I have a tested and validated routine which does this.

I know that I am expecting the weekly model to fit perfectly, and the other two won't. To dot his on paper would require ~300 equation calcs to get the values I am working with and then work out the R^2 value. I would rather not do that...

How can I test this code? I am new to Unit Testing as a concept and am still understanding the paradigms used when testing functions.

My Code:

Where History and Graph are Vectors of Vectors.

float calculateDeviation(int period) {
    int x1 = history.front()[0];
    int x2 = x1 + period;
    int i = 0, minimum, maximum, SSres = 0, SStot = 0, j=0, R2 =0;
    float  average = 0;
    int endTime = history.back()[0];
    while (x2 <= history.back()[0]) {
        average += averageGradient(x1, x2);
        x1 = x2;
        x2 += period;
    }

    x1 = history.front()[0];
    x2 = x1 + period;
    i++;
    while (j < i) {
        SSres += pow((graph[i][0]-((graph[i][2]*graph[i][0])+graph[i][3])), 2);
        SStot += pow(graph[i][0] - average, 2);
        x1 = x2;
        x2 =+ period;
        j++;
    }

    R2 = 1 - (SSres / SStot);
    return history.back()[0];
}

I'm a practicing Test Engineer, and based on what you've provided, you should be able to write a basic unit test with the following:

  1. Prepare your input data. This means your "period" variable, as well as sample graph data. As the author of your graphs and logic, you should be able to create a simple data set that other engineers can understand.
  2. Prepare your response data. This means "the answer". No test is complete without a data-set to compare the results against.
  3. In the Unit Test, simply pass in the proper input data, and validate the results against pre-verified values.

Remember to prepare several sets of input data, including boundaries (minimums, maximums, and values that should fail). This is often the breaking point, so be sure to run tests that require error handling. If you can think of a way to break your code, then you've successfully identified an area that needs some tweaking. And that, my friend, is the entire point. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM