Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NUnit to test for any type of exception

Tags:

c#

.net

nunit

I have a class that creates a file.

I am now doing integration tests to make sure the class is ok.

I am passing in invalid directory and file names to make sure exceptions are thrown.

In my tests are I am using:

[Test] public void CreateFile_InvalidFileName_ThrowsException() {     //Arrange     var logger = SetupLogger("?\\");      //Act      //Assert     Assert.Throws<Exception>(()=> logger.CreateFile());  } 

However in this scenario the test is failing as an ArgumentException is thrown. I thought by adding just Exception it would pass.

Is there a way to make this pass just using Exception?

like image 244
Jon Avatar asked Mar 27 '12 11:03

Jon


People also ask

What type of testing does NUnit support?

NUnit is an open-source unit testing framework for the . NET Framework and Mono. It serves the same purpose as JUnit does in the Java world, and is one of many programs in the xUnit family.

Can NUnit test private methods?

Just like other classes can interact only with the public methods of your class, the same should apply to a unit test. The unit test should only test the public interface. Each private method is an implementation detail. They contain the logic necessary to implement a piece of functionality.

Can NUnit be used for integration testing?

ASP.NET Core has an extremely useful integration testing framework, in the form of the NuGet package Microsoft.


1 Answers

The help for Assert.Throws<> states that it "Verifies a delegate throws a particular type of exception when called"

Try the Assert.That version as it will catch any Exception:

private class Thrower {     public void ThrowAE() { throw new ArgumentException(); } }  [Test] public void ThrowETest() {     var t = new Thrower();     Assert.That(() => t.ThrowAE(), Throws.Exception); } 
like image 148
Ritch Melton Avatar answered Oct 03 '22 01:10

Ritch Melton