C#的Unit Test如何根据exception来判断函数是否执行正确

添加ExpectedException属性, 然后指定异常类型, catch后决定Assert.IsTrue

The following class contains the method to test:

using System;

namespace MyCSNamespace
{
    public class DivisionClass
    {
        public int Divide(int numerator, int denominator)
        {
            return numerator / denominator;
        }
    }
}

The following test method tests the Divide method of the DivisionClass object. It tests for the existence of a DivideByZeroException.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyCSNamespace;

namespace MyCSTestProject
{
    [TestClass()]
    public class DivisionClassTest
    {
        [TestMethod()]
        [ExpectedException(typeof(System.DivideByZeroException))]
        public void DivideTest()
        {
            DivisionClass target = new DivisionClass();
            int numerator = 4;
            int denominator = 0;
            int actual;
            actual = target.Divide(numerator, denominator);
        }
    }
}

posted @ 2013-07-03 15:05  muzizongheng  阅读(1137)  评论(0编辑  收藏  举报
如果我们时时忙着展现自己的知识, 将何从忆起成长所需的无知?