Is there a more elegant way to do this test?

2 posts, 1 answers
  1. Lukas
    Lukas avatar
    20 posts
    Member since:
    Jul 2011

    Posted 05 Jun 2012 Link to this post

    Normally you test, if an exception gets thrown in a certain method, as follows. 
    I use FluentAssertions:
    
            [Fact]
            public void Exception_gets_thrown()
            {
                var foo = new Foo("validArgument");
     
                foo.Invoking(f => f.Bar(null))		// null is an invalid argument
                   .ShouldThrow<ArgumentNullException>();
            }
    But how to test if an exception gets thrown in the constructor. I just did it like this, but is there maybe a more appropriate way via FluentAssertions?


            [Fact]
            public void Constructor_throws_Exception()
            {
                Action a = () => new Foo(null);		// null is an invalid argument
                a.ShouldThrow<ArgumentNullException>();
            }
  2. Answer
    Ricky
    Admin
    Ricky avatar
    467 posts

    Posted 08 Jun 2012 Link to this post

    Hi Lukas,

    Thanks again for bringing up the question. 

    If you just want to test if a constructor throws an exception, you can use Assert.Throws/ExepectedException to check if the constructor is throwing the expected exception.

    However, if you rather intend to mock the constructor you can easily do it by this line:

    var  foo = Mock.Create<Foo>(Constructor.Mocked);
     

    Kind Regards
    Ricky
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

  3. DevCraft R3 2016 release webinar banner
Back to Top