简体   繁体   English

如何在另一个类引发的测试类中捕获异常?

[英]How to catch an Exception in test class which is thrown by another class?

I have a window form with one button and I am trying to test it with codedUitest. 我有一个带有一个按钮的窗口表单,我正在尝试使用codedUitest对其进行测试。 I want the test to fail if any exception is thrown but in the test class it doesn't catch the exception. 如果要抛出任何异常,我希望测试失败,但是在测试类中,它无法捕获异常。

Here is my code: 这是我的代码:

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;  
    }
}

The test method is: 测试方法是:

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

You've written an integration test. 您已经编写了集成测试。

Disclaimer: I'm a web dev - so I have to assume this is similar to using a browser driver like selenium. 免责声明:我是一名Web开发人员-所以我必须假定这类似于使用浏览器驱动程序(例如selenium)。

So what you're doing is telling a UI driver to click the button . 因此,您要做的就是告诉UI驱动程序单击按钮 This runs the code but it doesn't run it in the test context . 这将运行代码,但不会在测试上下文中运行它 Your test only has access to the UI. 您的测试只能访问UI。

In order to detect whether or not the error has been thrown, I guess you'll have to inspect the UI to see if a popup has appeared. 为了检测是否已引发错误,我想您必须检查UI才能查看是否出现了弹出窗口。

If you want to test just the method (which might be preferable depending on your situation) you can use NUnit and Moq. 如果只想测试该方法(根据情况可能更合适),则可以使用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;
            }

        }
    }
}

You can add [ExpectedException(typeof(IndexOutOfRangeException))] attribute to your TestMethod. 您可以将[ExpectedException(typeof(IndexOutOfRangeException))]属性添加到TestMethod。 Have a look at MSTest Exception Handling . 看一下MSTest异常处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM