【问题标题】:How to catch an Exception in test class which is thrown by another class?如何在测试类中捕获另一个类抛出的异常?
【发布时间】:2015-08-24 14:43:42
【问题描述】:

我有一个带有一个按钮的窗口窗体,我正在尝试使用 codedUitest 对其进行测试。如果抛出任何异常,我希望测试失败,但在测试类中它不会捕获异常。

这是我的代码:

public void button1_Click(object sender, EventArgs e)
{ 
    double[] dummy = new double[1];
    int i = 1;

    if (i > 0)
    {
        throw new System.IndexOutOfRangeException("index parameter is out of range.");      
    }
    else
    {             
        dummy[i] = 6;  
    }
}

测试方法是:

public void CodedUITestMethod1()
{
    try
    {
        this.UIMap.TryBtn1();
    }
    catch (IndexOutOfRangeException)
    {
        Assert.Fail();
    }
}

【问题讨论】:

标签: c# exception-handling coded-ui-tests


【解决方案1】:

您已经编写了一个集成测试。

免责声明:我是一名网络开发人员 - 所以我必须假设这类似于使用像 selenium 这样的浏览器驱动程序。

所以你正在做的是 告诉 UI 驱动程序点击按钮。这会运行代码,但它不在测试上下文中运行它。您的测试只能访问 UI。

为了检测是否抛出了错误,我想你必须检查 UI 以查看是否出现了弹出窗口。

如果您只想测试方法(根据您的情况可能更可取),您可以使用 NUnit 和 Moq。

using System;
using Moq;
using NUnit.Framework;

namespace Tests
{
    [TestFixture]
    class Tests
    {
        [Test]
        public void Throws()
        {
            var sender = new Mock<object>();
            var args = new Mock<EventArgs>();

            Assert.Throws<IndexOutOfRangeException>(() => button1_Click(sender.Object, args.Object));
        }

        public void button1_Click(object sender, EventArgs e)
        {
            double[] dummy = new double[1];
            int i = 1;

            if (i > 0)
            {

                throw new System.IndexOutOfRangeException("index parameter is out of range.");
            }
            else
            {
                dummy[i] = 6;
            }

        }
    }
}

【讨论】:

    【解决方案2】:

    您可以将[ExpectedException(typeof(IndexOutOfRangeException))] 属性添加到您的TestMethod。看看MSTest Exception Handling。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2012-01-12
      • 1970-01-01
      • 2018-02-13
      • 2012-02-09
      • 2021-01-21
      相关资源
      最近更新 更多