每当我想练习某种代码路径时,否则只能在难以重现的情况下达到,condition
例如:
if (condition) { code to be tested }
我or
有一个true
值:
if (true || condition) { code to be tested }
有没有更优雅的方法?
每当我想练习某种代码路径时,否则只能在难以重现的情况下达到,condition
例如:
if (condition) { code to be tested }
我or
有一个true
值:
if (true || condition) { code to be tested }
有没有更优雅的方法?
更优雅的解决方案是使用模拟。根据依赖关系或参数做出决策:
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.IsBar).Returns(true);
var sut = new Sut(mock.Object);
sut.DoSomething();
在您的测试系统中:
public void DoSomething()
{
if (_foo.IsBar)
// code path to test
}
我认为更多elegant way
的是使用the logical negation operator (!)
as;
if (!condition) { code to be tested }
但更安全的调试或测试方式,您可以使用预处理器指令(根据我的评论)。完成测试后,只需删除或更改#define UnreachableTest
#define UnreachableTest //should be on the top of the class/page
#if (UnreachableTest)
condition = !condition; //or
condition = true;
#endif
if (condition) { code to be tested }
您使用“真或”的方法和 if (!condition) 的方法是最简单的。这是我喜欢大型程序的一种方法
创建一个函数,我们称之为 testme(const string)。而不是在 if 测试中插入 true,而是插入 testme,并带有一些标识那段代码的字符串。
if ( testme("Location 123") || condition ) { code to be tested }
然后,使用某种配置文件或程序的参数(我更喜欢配置),您可以完全控制 testme("Location 123") 何时返回 true。并且您可以在许多地方使用相同的功能。只需更改配置文件以测试每个。
我假设这不是单元测试场景,因为问题中没有提到它。到目前为止,对这样的代码进行动态测试的最简单方法是使用调试器的 Set Next Statement 命令。
如有必要,在 if() 语句上设置断点,或单步执行代码直到到达该语句。然后右键单击 if() 语句主体内的下一行,然后选择“设置下一个语句”。代码将在该行继续执行,完全跳过 if()。
将要测试的代码放在单独的方法中。然后您可以调用该方法并绕过条件。现在您不必担心添加“true”或更重要的是忘记删除它。
您还可以为该方法添加单元测试,以便您可以修改传递给它的参数并测试您想要的所有场景。