Search code examples
c++visual-studiogoogletest

Visual Studio's gtest unit calculates incorrect code coverage


I try to use gtest in visual studio enterprise 2022 and generate code coverage.

// pch.h
#pragma once
#include <gtest/gtest.h>

// pch.cpp
#include "pch.h"

// test.cpp
#include "pch.h"
int add(int a, int b) {
    return a + b;
}
TEST(a, add) {
    EXPECT_EQ(2, add(1, 1));
}

This image is my test coverage report: This image is my test coverage report.

Such a minimalist code. I think its code test coverage should be 100%. But in reality it's only 26.53%. I think it might be because a lot of stuff in the header file "gtest/gtest.h" is not executed. Please tell me how to write a hello world project with 100% coverage.


Solution

  • You should write tests in dedicated files and exclude test sources from analysis by test coverage tools. Unit tests are not subjects of any test coverage tools by their nature.

    // First file, a subject for a tool
    int add(int a, int b) {
        return a + b;
    }
    
    // Second file, excluded from analysis by a tool
    TEST(a, add) {
        EXPECT_EQ(2, add(1, 1));
    }
    

    TEST produces a lot of code that include several conditional branches, exception handlers and other stuff.

    EXPECT_EQ produces at least two branches if (2 == add(1, 1) ... else ....

    Of course add(1, 1) gives a single result and is unable to cover all branches in the unit test.