NUnit 3.0 and Assert.Throws

前端 未结 3 1475
盖世英雄少女心
盖世英雄少女心 2020-12-05 03:55

I am writing some unit tests with NUnit 3.0 and, unlike v2.x, ExpectedException() has been removed from the library.

Based on this answer, I can definit

相关标签:
3条回答
  • 2020-12-05 04:11

    In C# 7, there is another option (albeit very similar to the existing answers):

    [Test]
    public void Should_not_convert_from_prinergy_date_time_sample2()
    {
        void CheckFunction()
        {
            //Arrange
            string testDate = "20121123120122";
    
            //Act
            testDate.FromPrinergyDateTime();
        }
    
        //Assert
        Assert.Throws(typeof(Exception), CheckFunction);
    }
    

    Blog post on the subject

    0 讨论(0)
  • 2020-12-05 04:28

    You can create a custom Attribute in NUnit 3. Here is the sample code how to create [ExpectedException] Attribute.(ExpectedExceptionExample Shows how to implement a custom attribute for NUnit) https://github.com/nunit/nunit-csharp-samples

    0 讨论(0)
  • 2020-12-05 04:34

    I see where you're coming from, even though I don't mind combining Act/Assert steps in this case.

    The only thing I can think of is to store the actual delegate (here to FromPrinergyDateTime) into a variable as the "act" step and then assert it:

    [Test]
    public void Should_not_convert_from_prinergy_date_time_sample2()
    {
        //Arrange
        string testDate = "20121123120122";
    
        //Act
        ActualValueDelegate<object> testDelegate = () => testDate.FromPrinergyDateTime();
    
        //Assert
        Assert.That(testDelegate, Throws.TypeOf<FormatException>());
    }
    

    I get that the "act" step isn't really acting, but rather defining what the action is. However, it does clearly delineate what action is being tested.

    0 讨论(0)
提交回复
热议问题