Domanda

I m using NUnit, I have following code which will be tested.

public class StudentPresenter
{
    IView myview;
    Repository myrepo;
    public StudentPresenter(IView vw, Data.Repository rep)
    {
        this.myview = vw;
        this.myrepo = rep;
        this.myview.ButtonClick += myview_ButtonClick;
    }

    public void myview_ButtonClick()
    {
        try
        {
         var d = this.myrepo.GetById(int.Parse(myview.GivenId));
         this.myview.GetStudent(d);
        }
        catch(Exception e)
        {
        }

    }
}


I need to test myview_ButonClick()
Lets suppose I will test this method and it will throw exception if myview.GivenId is null?
So I write unit test as below:

[Test]       
public void Button1Click_NullText_ThrowException()
{
    var mock = Substitute.For<IView>();
    StudentPresenter sp = new StudentPresenter(mock, repo);
    mock.GivenId = string.Empty;
    Assert.Throws<Exception>(()=>sp.myview_ButtonClick());
}


But test failed.. Why? (becouse no throw in my catch block). But I dont want to throw anything, I just want that it has to ability to catch. So is it possible to test?

È stato utile?

Soluzione

You cannot have a unit test that checks if a code block has a "catch" block. The only way to (indirectly) do it would be to test that the test does not throw when given input that would normally cause it to throw.

NUnit has a DoesNotThrow assert that should be useful here.

Of course, that's no guarantee of the existence of a try/catch, but its about the best you can do.

Altri suggerimenti

myview_ButtonClick() catches all exceptions, and so it will never throw an exception that could be detected from outside the method, hence your test fails.

If you want to catch the exception, do something with it, and then throw it in order for a caller to catch it, or the test to pass, then simply

catch (Exception e)
{
    //actions....
    throw;
}

Bear in mind too that catching all exceptions is rarely a good idea. The calling code will continue oblivious to the exception state, and this could cause untold problems down the line, which could be a nightmare to debug and track down.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top