2013-09-16 92 views
-1

我使用C#进行测试。测试包含几个测试步骤。如果一个测试步骤失败,整个测试应该中止。一个测试步骤可能看起来像这样:返回调用函数

Variable1.Value = 1; 
Variable1.write(); 

Variable1.read(); 
if (Variable1.Value != 1) 
{ 
    Console.WriteLine("Fail"); 
    return; //this return aborts the test 
} 
//next test steps 

我想一些命令转移到自己的功能允许有效的测试用例编程。上面代码的功能看起来像这样。

private void verifyValue (TypeOfVariable Var, double Value) 
{ 
    Var.read(); 
    if (Var.Value != Value) 
    { 
     Console.WriteLine("Fail"); 
     return; 
    } 
} 

并且测试是这样的

Variable1.Value = 1; 
Variable1.write(); 
verifyValue(Variable1, 1); 
//next test steps 

我的问题是现在,认为return在功能verifyValue只影响verifyValue但不调用函数(又名测试)。

有没有可能中止调用函数?

+4

是否有任何理由你没有使用单元测试框架和'断言'? –

+3

您正试图通过使用返回语句和函数完成来实现原子操作。我认为这不是一个很好的方法。相反,您可以实现将所有语句作为事务执行的类,并根据它们抛出的异常,可以中止或继续操作。 – Slavo

+1

除非你的例子非常糟糕,我同意@Slavo。这不是如何实现你想要实现的。在说,一个昂贵的,但可能的选择是抛出一个例外。 –

回答

0

它更好,如果你使用交易,然后在任何异常中止所有的操作。对于您当前的代码,您可以通过异常让程序自行停止。如:

throw new Exception("Test Failed - Stopping the program execution"); 
1

这通常通过Exceptions完成。它们自动传播通过堆栈。这里有一个基于你的代码的例子:

public class TestFailedException : Exception 
{ 
    public TestFailedException(string message) : base(message) { } 
} 

void Test() 
{ 
    try 
    { 
     Variable1.Value = 1; 
     Variable1.write(); 
     verifyValue(Variable1, 1); 

     //next test steps 
     ... 

     Console.WriteLine("Test succeeded"); 
    } 
    catch (TestFailedException ex) 
    { 
     Console.WriteLine("Test failed: " + ex.Message); 
    } 
} 

private void verifyValue(TypeOfVariable Var, double Value) 
{ 
    Var.read(); 
    if (Var.Value != Value) 
    { 
     throw new TestFailedException("Actual value: " + Var.Value.ToString() 
      + ", expected value: " + Value.ToString()); 
    } 
}