Right now, we have exactly one slow test for the WAV Snippet Publisher codebase. We’ll strive to keep it that way. But if you need another file-based utility, you’d want to ensure you don’t add a second slow test. Once you allow them, slow tests add up quickly.
One possible solution is to separate out the portion of the functionality that deals only with the stream and test-drive it. For the size function, we could create an even smaller method.
wav/12/StreamUtilTest.cpp | |
| TEST(StreamUtil_Size, AnswersNumberOfBytesWrittenToStream) { |
| istringstream readFrom{"abcdefg"}; |
| |
| CHECK_EQUAL(7, StreamUtil::size(readFrom)); |
| } |
wav/12/StreamUtil.cpp | |
| std::streamsize size(std::istream& stream) { |
| stream.seekg(0, std::ios::end); |
| return stream.tellg(); |
| } |
FileUtil’s size function would simply delegate work to StreamUtil’s size function, passing it the ifstream. We might consider the resulting FileUtil function to be so small as to not break and consider not writing a unit test for it.
We could also create a FileUtil function, execute, whose sole job is to create an ifstream and pass it to a function that operates on that stream. Client code would pass a function pointer to execute.
wav/12/FileUtilTest.cpp | |
| streamsize size = util.execute(TempFileName, |
| [&](istream& s) { return StreamUtil::size(s); }); |
wav/12/FileUtil.h | |
| std::streamsize execute( |
| const std::string& name, |
| std::function<std::streamsize (std::istream&)> func) { |
| std::ifstream stream{name, std::ios::in | std::ios::binary}; |
| return func(stream); |
| } |
The benefit is that we’d need only one test—for the execute function—that handled files. All other tests would be fast, stream-only tests.
3.141.28.107