How to extract testing creation logic into a shared method
I have code I want to extract from a unit test to make my test method clearer:
Check check;
check.Amount = 44.00;
// unit testing on the check goes here
How should I extract this? Should I use a pointer to the check or some other structure to make sure it's still allocated when I use the object?
I don'开发者_Python百科t want to use a constructor because I want to isolate my test creation logic with production creation logic.
In a modern unit testing framework you usually have testing case as
class MyTest: public ::testing::Test {
protected:
MyTest() {}
~MyTest() {}
virtual void SetUp() {
// this will be invoked just before each unit test of the testcase
// place here any preparations or data assembly
check.Amount = 44.00;
}
virtual void TearDown() {
// this will be inkoved just after each unit test of the testcase
// place here releasing of data
}
// any data used in tests
Check check;
};
// single test that use your predefined preparations and releasing
TEST_F(MyTest, IsDefaultInitializedProperly) {
ASSERT_FLOAT_EQ(44., check.Amount);
}
// and so on, SetUp and TearDown will be done from scratch for every new test
You can find such functionality i.e. in Google Test Framework (https://github.com/google/googletest/)
精彩评论