Reputation: 992707
I have a module that uses std::string
as part of its interface. I would like to run a unit test on this module using bounds checking on index access of the std::string
. That is, if a string s
has only 5 characters, I would like to throw an exception of some kind when accessing s[5]
(or s[-1]
).
Here is the basics of my code. The module is all implemented in a single header file.
#include <string>
int decode(const std::string &data) { ... }
#include "module.h"
#include "gtest/gtest.h" // using Google Test
TEST(Module, Decode) {
ASSERT_EQ(decode("...") == 5); // or whatever
}
I suppose one way would be to implement the module.h
in terms of templates, where the implementation depends on some type that allows indexing. However, there's no reason for the implementation in module.h
to use anything other than std::string
in the real world; such a feature would only be used for unit testing. I'd rather not use templates here.
I'm okay with using preprocessor tricks as long as the tricks are limited to the test.cpp
module. For example, I don't want to have to #define ModuleString std::string
before including module.h
under normal circumstances.
What are my options here?
Upvotes: 1
Views: 1249
Reputation: 32240
Instead of the operator[]
, you could use std::string::at
, which already does boundary checking and throws std::out_of_range
. Feasible?
Upvotes: 4