【发布时间】:2012-11-09 14:31:15
【问题描述】:
我是 TDD 和 C++ 的大一新生,我写了一些代码作品但看起来很难看...
您能给我一些关于如何重构这些代码的提示吗?
我这样定义测试用例:
// define some test case
namespace test_case_planes {
const std::string t_filename = "planes.segy_first_trace";
boost::uintmax_t t_file_size = 5888;
boost::uintmax_t t_traces_size = 1;
boost::int16_t t_trace_samples_size = 512;
boost::int16_t t_sample_interval = 4000; // 2000us, 2ms
}
namespace test_case_ld0042_file_00018 {
const std::string t_filename = "ld0042_file_00018.sgy_first_trace";
boost::uintmax_t t_file_size = 12040;
boost::uintmax_t t_traces_size = 1;
boost::int16_t t_trace_samples_size = 2050;
boost::int16_t t_sample_interval = 2000; // 2000us, 2ms
}
并像这样测试(用谷歌测试)
TEST(Segy, constructWithNoParas){
using namespace test_case_planes;
segy::Segy* test_segy = new segy::Segy();
EXPECT_EQ(test_segy->getFilename(), t_filename);
}
TEST(Segy, constructWithFilename){
using namespace test_case_ld0042_file_00018;
segy::Segy* test_segy = new segy::Segy(t_filename);
EXPECT_EQ(test_segy->getFilename(), t_filename);
}
TEST(Segy, setFilename){
using namespace test_case_ld0042_file_00018;
segy::Segy* test_segy = new segy::Segy();
test_segy->setFilename(t_filename);
EXPECT_EQ(test_segy->getFilename(), t_filename);
}
【问题讨论】:
-
“看起来很丑”似乎有点模糊的问题。你希望什么?
-
这些测试对我来说实际上看起来不错。如果你指的是一些重复的代码,在单元测试的上下文中是可以接受的,只要测试的意图是明确的。我将向您推荐一般适用于单元测试的 Pylons/Pyramid 测试指南:docs.pylonsproject.org/en/latest/community/testing.html
-
@Cagez 代码重复是不可接受的。不在生产代码中,也不在测试代码中。绝不。测试代码必须像生产代码一样干净和可维护。否则,生产代码的更改会因为愚蠢的单元测试而变得昂贵......“让我们停止 tdd,它的工作量太大了”。那么,如何重构测试代码是一个很好的问题。
-
@hansmaad 我不同意。是的,不重复代码是最重要的编程美德之一,但这是一个例外。在可读性和可维护性方面,明确的单元测试意图优先于 DRY。正如文章所述,我并不是说完全放弃 DRY,而是不要为了聪明而妥协明确的测试意图。
-
@Cagez 感谢您的指导链接
标签: c++ unit-testing refactoring tdd