开发者

Zero division does not throw exception in nunit

开发者 https://www.devze.com 2023-01-01 10:48 出处:网络
Running the following C# code through NUnit yields Test.ControllerTest.TestSanity: Expected: `<System.DivideByZeroException>` But was:null

Running the following C# code through NUnit yields

Test.ControllerTest.TestSanity: Expected: `<System.DivideByZeroException>` But was:  null

So either no DivideByZeroException is thrown, or NUnit does not catch it. Similar to this question, but the answers he got, do not seem to work for me. This is using NUnit 2.5.5.10112, and .NET 4.0.30319.

    [Test]
    public void TestSani开发者_StackOverflow社区ty()
    {
        Assert.Throws<DivideByZeroException>(new TestDelegate(() => DivideByZero()));
    }

    private void DivideByZero()
    {
        // Parse "0" to make sure to get an error at run time, not compile time.
        var a = (1 / Double.Parse("0"));
    }

Any ideas?


No exception is thrown. 1 / 0.0 will just give you double.PositiveInfinity. This is what the IEEE 754 standard specifies, which C# (and basically every other system) follows.

If you want an exception in floating point division code, check for zero explicitly, and throw it yourself. If you just want to see what DivideByZeroException will get you, either throw it manually or divide integers by integer zero.


From MSDN:

The exception that is thrown when there is an attempt to divide an integral or decimal value by zero.

You are dealing with double, not any of the integral types (int etc) or decimal. double doesn't throw an exception here, even in a checked context. You just get +INF.

If you want to evaluate as integral math (and get the exception), use:

var a = (1 / int.Parse("0"));
0

精彩评论

暂无评论...
验证码 换一张
取 消