Expecting googlemock calls from another thread

后端 未结 5 620
挽巷
挽巷 2021-01-11 11:26

What will be the best way to write (google) test cases using a google mock object and expect the EXPECT_CALL() definitions being called from another thread controlled by the

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 12:25

    Using lambdas, you could do something like (I have put boost equivalents in comments):

    TEST_F(BarTest, DoSomethingWhenFunc2Gt0)
    {
        std::mutex mutex;                  // boost::mutex mutex;
        std::condition_variable cond_var;  // boost::condition_variable cond_var;
        bool done(false);
    
        EXPECT_CALL(fooInterfaceMock, func1())
            .Times(1);
        EXPECT_CALL(fooInterfaceMock, func2())
            .Times(1)
            .WillOnce(testing::Invoke([&]()->int {
                std::lock_guard lock(mutex);  // boost::mutex::scoped_lock lock(mutex);
                done = true;
                cond_var.notify_one();
                return 1; }));
    
        bar.start();
        bar.triggerDoSomething();
        {
          std::unique_lock lock(mutex);               // boost::mutex::scoped_lock lock(mutex);
          EXPECT_TRUE(cond_var.wait_for(lock,                     // cond_var.timed_wait
                                        std::chrono::seconds(1),  // boost::posix_time::seconds(1),
                                        [&done] { return done; }));
        }
        bar.stop();
    }
    

    If you can't use lambdas, I imagine you could use boost::bind instead.

提交回复
热议问题