1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include <string> 17 #include <thread> 18 #include "gtest/gtest.h" 19 #define private public 20 #include "CallbackQueue.h" 21 22 namespace { TEST(CallbackQueueTest,AddCallbackTest)23 TEST(CallbackQueueTest, AddCallbackTest) 24 { 25 CallbackQueue queue; 26 bool callbackCalled = false; 27 28 // 添加回调函数到队列中 29 queue.AddCallback([&callbackCalled]() { 30 callbackCalled = true; 31 }); 32 33 // 执行队列中的回调函数 34 queue.ConsumingCallback(); 35 36 // 验证回调函数是否被调用 37 EXPECT_TRUE(callbackCalled); 38 } 39 TEST(CallbackQueueTest,ConsumingCallbackTest)40 TEST(CallbackQueueTest, ConsumingCallbackTest) 41 { 42 CallbackQueue queue; 43 44 // 添加多个回调函数到队列中 45 for (int i = 0; i < 5; ++i) { 46 queue.AddCallback([]() { 47 std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟耗时操作 48 }); 49 } 50 51 // 启动多个线程同时执行 ConsumingCallback() 方法 52 std::vector<std::thread> threads; 53 for (int i = 0; i < 3; ++i) { 54 threads.emplace_back([&queue]() { 55 queue.ConsumingCallback(); 56 }); 57 } 58 59 // 等待所有线程执行完成 60 for (auto& thread : threads) { 61 thread.join(); 62 } 63 64 // 验证队列中的回调函数是否都被执行完毕 65 EXPECT_EQ(queue.callBackList.size(), 0); 66 } 67 }