Using try / catch blocks in unit tests

Using the VS testing framework, I am now writing my tests as follows:

[TestMethod]
public void TestSomething() 
{
    try
    {
        var someTestValue = _someTestClass.SomeTestMethod();            

        Assert.IsNotNull(someTestValue);
    }
    catch (Exception e) 
    {
        Assert.Fail(e.Message);
    }
}

My logic is that if an exception is thrown in SomeTestMethod(), I will immediately end the test displaying the exception message through Assert.Fail(e.Message).

"Normal way" of actions:

[TestMethod]
public void TestSomething() 
{
    var someTestValue = _someTestClass.SomeTestMethod();            

    Assert.IsNotNull(someTestValue);
}

Is my approach right or is this the normal way? Am I writing redundant code?

+4
source share
5 answers

, , . , . , , , . , - .

+5

, . .

+2

. Test .

+2

- , :

[TestMethod]
[ExpectedException(typeof(//Here the exception you expect))]  <------------
public void TestSomething() 
{
//Your test code
}

, , .

, try/catch . , - , ;)

,

+1

See this tutorial; there is an example unit test using the attribute [expectedException ()]: [Tutorial for ExpectedException Unit tests] [1]

  [1]: http://msdn.microsoft.com/en-us/library/hh694602%28v=vs.110%29.aspx#BKMK_Writing_your_tests
0
source

Source: https://habr.com/ru/post/1532194/


All Articles