简体   繁体   English

gtest:仅当必须运行特定装置时才执行某些操作的最佳方法是什么?

[英]gtest: What is the best way to perform some actions only when the specific fixture must be run?

I have a class derived from::testing::Test and several fixtures in it.我有一个派生自::testing::Test 的类和其中的几个固定装置。 I've also reimplemented SetUpTestCase method which must start the side application needed for those tests.我还重新实现SetUpTestCase方法,该方法必须启动这些测试所需的辅助应用程序。 But now I want to add a new fixture which needs that side application to be started with some additional arguments to enable logging.但是现在我想添加一个新的固定装置,它需要使用一些额外的参数来启动该端应用程序以启用日志记录。 The problem is, I want it to be logged only if I'm sure that the new test is in the run-list and will not be missed, otherwise the logging is not necessary.问题是,我希望仅当我确定新测试在运行列表中并且不会错过时才记录它,否则不需要记录。 So I'd like to write something like that:所以我想写这样的东西:

class MyTest : public ::testing::Test
{
public:
    static void SetUpTestCase()
    {
        std::vector<std::string> args;
        args.push_back("--silent");

        // if (TestLogging fixture will be run)
            args.push_back("--enableLog");

        //Start the side application with arguments "args"
    }
};

TEST_F(MyTest, Test1)
{/**/}
TEST_F(MyTest, Test2)
{/**/}
TEST_F(MyTest, TestLogging)
{/**/}

Is there any way to reach the behavior I expect?有什么办法可以达到我期望的行为吗? Or maybe I shouldn't mess up with SetUpTestCase and there is a better way to do this?或者也许我不应该搞砸SetUpTestCase并且有更好的方法来做到这一点?

You could query the test name both at SetUp and TearDown and match it against TestLogging .您可以在SetUpTearDown查询测试名称并将其与TestLogging匹配。

In case you wanted to have more than one logging test, you could name them with a TestLogging suffix, and check if the test name starts with that suffix.如果您想要进行多个日志记录测试,您可以使用TestLogging后缀命名它们,并检查测试名称是否以该后缀开头。

SetUp would then do the additional setup stuff, and TearDown would revert it.然后SetUp会做额外的设置工作,而TearDown会还原它。

[Demo] [演示]

class MyTest : public ::testing::Test {
protected:
    inline static std::vector<std::string> args{};
public:
    inline static void SetUpTestCase() {
        args.push_back("--silent");
    }
    virtual void SetUp() {
        std::string test_name{ testing::UnitTest::GetInstance()->current_test_info()->name() };
        if (test_name.starts_with("TestLogging")) {
            args.push_back("--enableLog");
        }
    }
    virtual void TearDown() {
        std::string test_name{ testing::UnitTest::GetInstance()->current_test_info()->name() };
        if (test_name.starts_with("TestLogging")) {
            args.pop_back();
        }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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