This is a migrated thread and some comments may be shown as answers.

Is there a more elegant way to do this test?

1 Answer 196 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Lukas
Top achievements
Rank 1
Lukas asked on 05 Jun 2012, 02:48 PM
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>();
        }

1 Answer, 1 is accepted

Sort by
0
Accepted
Ricky
Telerik team
answered on 08 Jun 2012, 05:04 PM
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 >>

Tags
General Discussions
Asked by
Lukas
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Share this question
or