测试难以到达的代码路径

Clo*_*eto 7 c#

每当我想要运用某些代码路径时,否则只能在难以复制的情况下达到condition:

if (condition) { code to be tested }
Run Code Online (Sandbox Code Playgroud)

or有一个true价值:

if (true || condition) { code to be tested }
Run Code Online (Sandbox Code Playgroud)

有更优雅的方法吗?

Ser*_*kiy 13

更优雅的解决方案是使用模拟.根据依赖关系或参数做出决策:

var mock = new Mock<IFoo>();
mock.Setup(foo => foo.IsBar).Returns(true);
var sut = new Sut(mock.Object);
sut.DoSomething();
Run Code Online (Sandbox Code Playgroud)

在您测试的系统中:

public void DoSomething()
{
    if (_foo.IsBar)
        // code path to test
}
Run Code Online (Sandbox Code Playgroud)

  • @Nogard我提到了嘲笑的用法.并添加了代码示例.在评论之前阅读结尾的答案. (4认同)

Kaf*_*Kaf 13

我认为更多的elegant way是使用the logical negation operator (!)as;

if (!condition) { code to be tested }
Run Code Online (Sandbox Code Playgroud)

但是更安全的调试或测试方法,您可以使用预处理器指令(根据我的常见问题).完成测试后,只需删除或更改即可#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 }
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,您可以使用`preprocessor directive`在调试期间更改测试目的的条件.如; `#define UnreachableTest`在顶部...`#if(UnreachableTest)condition =!condition#endif`然后你的实际代码要遵循. (5认同)
  • 对不起,我必须在这个答案上给出-1.这是一个非常糟糕的代码气味,可以改变逻辑条件来进行测试.它很危险,因为它可能导致有人忘记删除"!" 并最终生成具有条件翻转和生成错误/错误的生产代码. (5认同)