1

I have a window form with one button and I am trying to test it with 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();
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 2
    see this post for catching exception in unit tests http://stackoverflow.com/questions/933613/how-do-i-use-assert-to-verify-that-an-exception-has-been-thrown – Prashant Aug 24 '15 at 14:45
  • what unit testing framework do you use? – xeraphim Aug 24 '15 at 14:47
  • http://stackoverflow.com/questions/8381042/catch-an-exception-thrown-by-another-form is good but i want to use it on application contain a lot of methods and it does't make sense to add a try catch block to each method and i am use .NET framework 4.5 – Abdelrahman Ezz Aug 24 '15 at 14:58

2 Answers2

0

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.

So what you're doing is telling a UI driver to click the button. This runs the code but it doesn't run it in the test context. Your test only has access to the 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.

If you want to test just the method (which might be preferable depending on your situation) you can use NUnit and 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;
            }

        }
    }
}
cohen990
  • 83
  • 8
0

You can add [ExpectedException(typeof(IndexOutOfRangeException))] attribute to your TestMethod. Have a look at MSTest Exception Handling.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Nikita Shrivastava
  • 2,978
  • 10
  • 20