178

Using Google Test 1.6 (Windows 7, Visual Studio C++). How can I turn off a given test? (aka how can I prevent a test from running). Is there anything I can do besides commenting out the whole test?

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
User
  • 62,498
  • 72
  • 186
  • 247

8 Answers8

255

The docs for Google Test 1.7 suggest:

If you have a broken test that you cannot fix right away, you can add the DISABLED_ prefix to its name. This will exclude it from execution. This is better than commenting out the code or using #if 0, as disabled tests are still compiled (and thus won't rot).

Example from the above documentation:

// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { ... }

class DISABLED_BarTest : public testing::Test { ... };

// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { ... }

If you have access to more recent versions of Google Test (the current version is v1.12.1), check out the GTEST_SKIP() macro suggested by jslmsca in the comments and Peter Bloomfield in another answer. From the sample in advanced.md:

TEST(SkipTest, DoesSkip) {
  GTEST_SKIP() << "Skipping single test";
  EXPECT_EQ(0, 1);  // Won't fail; it won't be executed
}

class SkipFixture : public ::testing::Test {
 protected:
  void SetUp() override {
    GTEST_SKIP() << "Skipping all tests for this fixture";
  }
};

// Tests for SkipFixture won't be executed.
TEST_F(SkipFixture, SkipsOneTest) {
  EXPECT_EQ(5, 7);  // Won't fail
}
Bill
  • 14,257
  • 4
  • 43
  • 55
  • 1
    just found it too and filters – User Aug 26 '11 at 17:01
  • 1
    @Bill, I found it just before you posted your comment... (and I put it up as an answer too). I then removed my comment, figuring it's obsolete... but that's some really good info! +1 – Kiril Aug 26 '11 at 17:05
  • 1
    But disabling is not skipping. Skipping is a temporary not available state (like not connected to internet) and is only detected dynamically in the setup call. Just mentioning it as this is the #1 google result 11 years later – Lothar Apr 07 '22 at 09:00
  • I agree with @Lothar because disabling makes it easy to forget that the test exists. Disabling will prevent it from appearing in the Test Explorer Window (VS2022 using Test for Google Adapter) so it's preferable to use GTEST_SKIP until the test can be fixed. – jslmsca Aug 04 '22 at 18:54
  • @jslmsca, this is a great addition to the answer if using a more modern version of Google Test. GTEST_SKIP (and VS2022 integration) didn't exist with Google Test 1.7 back in 2011. :D – Bill Sep 09 '22 at 12:55
81

You can also run a subset of tests, according to the documentation:

Running a Subset of the Tests

By default, a Google Test program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the GTEST_FILTER environment variable or the --gtest_filter flag to a filter string, Google Test will only run the tests whose full names (in the form of TestCaseName.TestName) match the filter.

The format of a filter is a ':'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.

A pattern may contain '*' (matches any string) or '?' (matches any single character). For convenience, the filter '*-NegativePatterns' can be also written as '-NegativePatterns'.

For example:

./foo_test Has no flag, and thus runs all its tests.
./foo_test --gtest_filter=* Also runs everything, due to the single match-everything * value.
./foo_test --gtest_filter=FooTest.* Runs everything in test case FooTest.
./foo_test --gtest_filter=*Null*:*Constructor* Runs any test whose full name contains either "Null" or "Constructor".
./foo_test --gtest_filter=-*DeathTest.* Runs all non-death tests.
./foo_test --gtest_filter=FooTest.*-FooTest.Bar Runs everything in test case FooTest except FooTest.Bar. 

Not the prettiest solution, but it works.

DerKasper
  • 167
  • 2
  • 11
Kiril
  • 39,672
  • 31
  • 167
  • 226
  • In my case, I need to put the filtering condition in quotes as * is recognized as a wildcard. – thd Apr 21 '22 at 09:51
65

You can now use the GTEST_SKIP() macro to conditionally skip a test at runtime. For example:

TEST(Foo, Bar)
{
    if (blah)
        GTEST_SKIP();

    ...
}

Note that this is a very recent feature so you may need to update your GoogleTest library to use it.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Peter Bloomfield
  • 5,578
  • 26
  • 37
  • 1
    This feature is not released yet. It's unlikely that it will be included in a 1.8.x branch, since only fixes are accepted there. 1.9 is not available yet, not even announced at this time. – ocroquette Apr 14 '19 at 07:11
  • 9
    `GTEST_SKIP()` is available from 1.10.0. – mattdibi Mar 25 '20 at 17:02
  • Sadly documentation is still scarce around this. It seems there is also `GTEST_SKIP_("some message")` (note the trailing underscore) – Brandlingo Apr 16 '20 at 15:27
  • 1
    It's `#define GTEST_SKIP() GTEST_SKIP_("")` in [gtest.h](https://github.com/google/googletest/blob/477998eefac3d55831e7f3974671ba22b8739b93/googletest/include/gtest/gtest.h#L1904) to allow an optional skip message. – sebkraemer Nov 18 '20 at 07:47
24

Here's the expression to include tests whose names have the strings foo1 or foo2 in them and exclude tests whose names have the strings bar1 or bar2 in them:

--gtest_filter=*foo1*:*foo2*-*bar1*:*bar2*
ashutosh
  • 451
  • 4
  • 5
  • in some environments, the pattern needs to be enclosed in single quotes ```--gtest_filter='*foo1*:*foo2*-*bar1*:*bar2*'``` – antman Jul 20 '22 at 12:11
14

I prefer to do it in code:

// Run a specific test only
//testing::GTEST_FLAG(filter) = "MyLibrary.TestReading"; // I'm testing a new feature, run something quickly

// Exclude a specific test
testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting"; // The writing test is broken, so skip it

I can either comment out both lines to run all tests, uncomment out the first line to test a single feature that I'm investigating/working on, or uncomment the second line if a test is broken but I want to test everything else.
You can also test/exclude a suite of features by using wildcards and writing a list, "MyLibrary.TestNetwork*" or "-MyLibrary.TestFileSystem*".

pilkch
  • 777
  • 7
  • 17
  • This is a great solution. I use it to exclude some tests by default if the filter is blank. They can be enabled with `export GTEST_FILTER='*'`. – Timmmm Jul 13 '17 at 14:24
  • Actually that doesn't work because the default is "`*`" not "". Instead I'll just use another environment variable that overrides the filter. – Timmmm Jul 13 '17 at 14:36
  • Where did you define the "filter"? Is it a string ? – beasone Feb 19 '19 at 21:34
  • I don't define it so I think it must be a global included from gtest/gtest.h? – pilkch Feb 20 '19 at 12:56
  • Seems like a great solution. Unfortunately, this doesn't seem 100% properly supported on Windows when linking dynamically and results in unresolved external symbol for the `filter` flag. Also, seems like the latest is to use `GTEST_FLAG_SET(filter, "-MyLibrary.TestWriting");` instead of `testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting";`. – Louis Langholtz Mar 14 '23 at 23:07
7

If more than one test are needed be skipped

--gtest_filter=-TestName.*:TestName.*TestCase
Vijay C
  • 4,739
  • 4
  • 41
  • 46
  • in some environments, the pattern needs to be enclosed in single quotes ```--gtest_filter='*foo1*:*foo2*-*bar1*:*bar2*'``` – antman Jul 20 '22 at 12:14
6

For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.

#include <gtest/gtest.h>

const bool skip_some_test = true;

bool some_test_was_run = false;

void someTest() {
   EXPECT_TRUE(!skip_some_test);
   some_test_was_run = true;
}

TEST(BasicTest, Sanity) {
   EXPECT_EQ(1, 1);
   if(!skip_some_test) {
      someTest();
      EXPECT_TRUE(some_test_was_run);
   }
}

This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.

Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.

As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.

The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.

You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.

David C. Bishop
  • 6,437
  • 3
  • 28
  • 22
  • I recommend using GTEST_SKIP() or GTEST_SKIP_("") to exit after runtime environment checks that you have to "live with", so the skipping is separately logged at the end, rather than as a pass or fail. – Gem Taylor May 12 '23 at 11:44
6

I had the same need for conditional tests, and I figured out a good workaround. I defined a macro TEST_C that works like a TEST_F macro, but it has a third parameter, which is a boolean expression, evaluated runtime in main.cpp BEFORE the tests are started. Tests that evaluate false are not executed. The macro is ugly, but it look like:

#pragma once
extern std::map<std::string, std::function<bool()> >* m_conditionalTests;
#define TEST_C(test_fixture, test_name, test_condition)\
class test_fixture##_##test_name##_ConditionClass\
{\
    public:\
    test_fixture##_##test_name##_ConditionClass()\
    {\
        std::string name = std::string(#test_fixture) + "." + std::string(#test_name);\
        if (m_conditionalTests==NULL) {\
            m_conditionalTests = new std::map<std::string, std::function<bool()> >();\
        }\
        m_conditionalTests->insert(std::make_pair(name, []()\
        {\
            DeviceInfo device = Connection::Instance()->GetDeviceInfo();\
            return test_condition;\
        }));\
    }\
} test_fixture##_##test_name##_ConditionInstance;\
TEST_F(test_fixture, test_name)

Additionally, in your main.cpp, you need this loop to exclude the tests that evaluate false:

// identify tests that cannot run on this device
std::string excludeTests;
for (const auto& exclusion : *m_conditionalTests)
{
    bool run = exclusion.second();
    if (!run)
    {
        excludeTests += ":" + exclusion.first;
    }
}

// add the exclusion list to gtest
std::string str = ::testing::GTEST_FLAG(filter);
::testing::GTEST_FLAG(filter) = str + ":-" + excludeTests;

// run all tests
int result = RUN_ALL_TESTS();
Jiri Zbranek
  • 61
  • 1
  • 1