每当我想要运用某些代码路径时,否则只能在难以复制的情况下达到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)
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)