您认为这是测试异常的好方法吗?有什么建议?
Exception exception = null;
try{
//I m sure that an exeption will happen here
}
catch (Exception ex){
exception = ex;
}
Assert.IsNotNull(exception);
Run Code Online (Sandbox Code Playgroud)
我正在使用MS Test.
如果我们做了
throw new ArgumentException("Cannot do that");
Run Code Online (Sandbox Code Playgroud)
你如何断言ArgumentException微软的测试框架发生了这种情况?
我想编写一个单元测试来检测抛出的异常.使用ExpectedExceptionAttribute,我从MSVS内部运行测试,当TestMethod遇到异常时,调试器会中断异常,但TestMethod会正确跳过并报告Passed.
是否有一面旗帜告诉VS在单元测试期间不要破坏?
在下面的测试中,如果它进入catch块,我想表明测试已经过去了.如果绕过catch块我希望测试失败.
有没有办法做到这一点,或者我错过了如何构建测试的重点?
[TestMethod]
public void CommandExecutionWillThrowExceptionIfUserDoesNotHaveEnoughEminence()
{
IUserCommand cmd = CreateDummyCommand("TEST", 10, 10);
IUser user = new User("chris", 40);
try
{
cmd.Execute(user);
}
catch(UserCannotExecuteCommandException e)
{
//Test Passed
}
// Test Failed
}
Run Code Online (Sandbox Code Playgroud) 我正在为一个应用程序进行单元测试,该应用程序有一个构造函数,它将三个值作为参数.数字应为0或更高,现在我正在编写一个单元测试,用于抛出异常的构造函数,如果不是这样的话.
我无法弄清楚的是我如何在"断言"之后写什么来确定这一点,以便在非法数字传递给构造函数时测试通过.提前致谢.
编辑:我正在使用MSTest框架
public void uniqueSidesTest2()
{
try {
Triangle_Accessor target = new Triangle_Accessor(0, 10, 10);
}
catch (){
Assert // true (pass the test)
return;
}
Assert. // false (test fails)
}
Run Code Online (Sandbox Code Playgroud)
//从代码中......
public Triangle(double a, double b, double c) {
if ((a <= 0) || (b <= 0) || (c <= 0)){
throw new ArgumentException("The numbers must higher than 0.");
}
sides = new double[] { a, b, c };
}
Run Code Online (Sandbox Code Playgroud) 我统一我有一个使用错误参数调用的函数,我想确保该函数使用正确的消息抛出正确的异常。所以我的函数调用是这样的:
winDetector.DoMove(move)
Run Code Online (Sandbox Code Playgroud)
它应该抛出这样的异常:
throw new Exception("Move is not valid.");
Run Code Online (Sandbox Code Playgroud)
看起来我应该使用Assert.Throws<Exception>,但我不知道如何使用。现在介绍 Unity 和 C#。我怎样才能做到这一点?
PSAssert.Throws<Exception>这不是正确的方法。请看我下面的回答。
例:
Assert.AreEqual(**null**, Program.nDaysMonth(5, -10), "Error nDaysMonth, Month may -10.");
Run Code Online (Sandbox Code Playgroud)
我期待一个例外.我怎么能在Assert.AreEqual中得到异常?
谢谢.