2016-02-12 22 views
1

我正在嘗試創建運行測試所需的字符串數組。我就是這麼做的。在googletest框架中的for循環中運行EXPECT_THROWD

TEST(ParseTest, UnknownType) { 
    String test_strings[] = { 
     String("X 1024\n"), 
     String("AB 1024\n") 
    }; 

    int test_strings_size = sizeof(test_strings)/sizeof(test_strings[0]); 

    for (int idx = 0; idx < test_strings_size; idx++) { 
     Transaction transaction; 
     String transaction_type = test_strings[idx]; 
     EXPECT_THROW(transaction.parse(transaction_type), ParseError); 
    } 
} 

但是,當我在谷歌測試框架運行它,我得到以下錯誤:

[==========] Running 1 test from 1 test case. 
[----------] Global test environment set-up. 
[----------] 1 test from ParseTest 
[ RUN  ] ParseTest.UnknownRequestType 
tests/transaction.cpp:20: Failure 
Expected: transaction.parse(transaction_type) throws an exception of type ParseError. 
    Actual: it throws nothing. 
[ FAILED ] ParseTest.UnknownRequestType (0 ms) 
[----------] 1 test from ParseTest (0 ms total) 

[----------] Global test environment tear-down 
[==========] 1 test from 1 test case ran. (0 ms total) 
[ PASSED ] 0 tests. 
[ FAILED ] 1 test, listed below: 
[ FAILED ] ParseTest.UnknownRequestType 

1 FAILED TEST 

當這應該實際運行兩個測試用例,它抱怨的只有一個。我錯過了什麼嗎?

回答

2

下面是一些澄清:

你實際上是運行一個測試用例,請參閱下面的定義:

TEST(TestCase, TestName) 

所以在測試結果時,它說:「1測試1測試案例跑」 ,'test'是指你的TestName字段(在你的情況下是UnknownType)和測試用例顯然是指'測試用例'(ParseTest)。無論您在特定測試中設置了多少個「ASSERTions」或「期望」,都無關緊要。它最終將被報告爲一項測試。

因此,如果您

TEST(TestCase1, Test1){ 
    ..... 
} 
TEST(TestCase1, Test2){ 
    .... 
} 

它將被報告爲:1個測試用例2周的測試跑

因此,假設「X 1024」是會造成異常的一個,我懷疑「AB 1024」(沒有例外)的結果是最終報告的結果。

1

我會寫一個value parameterized test以獲得更方便的測試結果。

實施例:

class ParseTest : public ::testing::TestWithParam<const String> {}; 

TEST_P(ParseTest, UnknownType) 
{ 
    Transaction transaction; 
    String transaction_type = GetParam(); 
    EXPECT_THROW(transaction.parse(transaction_type), ParseError); 
} 

INSTANTIATE_TEST_CASE_P(UnknownTypeInstance, 
         ParseTest, 
         ::testing::Values(String("X 1024\n"), String("AB 1024\n")));