Asserting an exception thrown from a mock object constructor

Assume: VS2010, .NET 4, C#, NUnit, Moq

I am new to TDD and came across this issue while working through a project.

Given the class:

public abstract class MyFileType
{                
    public MyFileType(String fullPathToFile)
    {
        if (!File.Exists(fullPathToFile))
        {
            throw new FileNotFoundException();
        }

        // method continues

    }
}

I am trying to test it using the method:

[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
    var mock = new Mock<MyFileType>(nonexistingPath);
}

The test fails and NUnit reports an exception was never thrown.

I did find a section in the NUnit docs talking about asserting with exceptions, but the examples didn't seem like what I am trying to do. I am still getting started with NUnit and Moq so I may be going about this the wrong way.

UPDATE:

To help clarify why this example uses an abstract class, it is the base class of a series file types where only the loading and disposing of the data would differ between subclassed types. My initial thought was to put the logic for open/setup into a base class since it is the same for all types.

If you have to have the class an abstract one, we should then just implement it as it's meant to be (simplicity): MSDN: an abstract class

So, agreeing (with alexanderb)that a mock is probably not needed here and also with Stecy on the .Throws NUnit Assert extension, you can create a class in the test that calls the base class as follows:

using System;
using System.IO;

namespace fileFotFoundException {
    public abstract class MyFile {

        protected MyFile(String fullPathToFile) {
            if (!File.Exists(fullPathToFile)) throw new FileNotFoundException();
        }
    }
}

namespace fileFotFoundExceptionTests {
    using fileFotFoundException;
    using NUnit.Framework;

    public class SubClass : MyFile {
        public SubClass(String fullPathToFile) : base(fullPathToFile) {
            // If we have to have it as an abstract class...
        }
    }

    [TestFixture]
    public class MyFileTests {

        [Test]
        public void MyFile_CreationWithNonexistingPath_ExceptionThrown() {
            const string nonExistingPath = "C:\\does\\not\\exist\\file.ext";

            Assert.Throws<FileNotFoundException>(() => new SubClass(nonExistingPath));
        }
    }
}

Mocking Exception Throwing using Mockito, Learn to configure a method call to throw an exception in Mockito. Assert an Exception is Thrown in JUnit 4 and 5. Have a look at how to test� If the expected exception is thrown, assertThrows returns the exception, which enables us to also assert on the message. Furthermore, it's important to note that this assertion is satisfied when the enclosed code throws an exception of type NullPointerException or any of its derived types.

The constructor will not be called until you reference mock.Object. That should trigger the exception you're expecting.

On a side note, it's generally bad practice to have a constructor throw exceptions other than usage exceptions (such as the various ArgumentException derivatives.) Most developers don't expect 'new' to throw an exception unless they've done something very wrong; a file not existing is the kind of exception that can legitimately happen beyond the control of the program, so you might want to make this a static factory method instead like "FromFileName". EDIT: Given that this is a base class constructor, that's not really applicable either, so you may want to consider where is the best place to institute this check. After all, the file may cease existing at any point, so it might not even make sense to check in the constructor (you'll need to check in all relevant methods anyway.)

Mock Exceptions Using MOQ, The key point to notice is the Throws method that lets you define an exception to be thrown when your mocked method is called. public class� The problem with any other approach but this is that they invariably end the test once the exception has been thrown. I, on the other hand, often still want to call org.mockito.Mockito.verify with various parameters to make sure that certain things happened (such that a logger service was called with the correct parameters) before the exception was thrown.

I faced similar problem today. I worked it out using the following solution:

[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    String nonexistingPath = "C:\\does\\not\\exist\\file.ext";
    var mock = new Mock<MyFileType>(nonexistingPath);
    try
    {
        var target = mock.Object;
    }
    catch(TargetInvocationException e)
    {
        if (e.InnerException != null)
        {
            throw e.InnerException;
        }
        throw;
    }
}

EasyMock - Exception Handling, EasyMock provides the capability to a mock to throw exceptions, so exception handling can be tested. Here we've added an exception clause to a mock object. the mock EasyMock.replay(calcService); //test the add functionality Assert. Ok, so, guys, we are mixing 3 unconnected things here: One debate is: Q1) should a method to test an exception is NOT thrown exist (yes/no)? Another debate is: in the case it does not exist, Q2) shoud an explanation exist in the documentation, such as explaining that there is NOT any method for that, so if you want to test exception-not-thrown you MUST implement your own logic with ifs or try

Assuming you're using the latest version of NUnit (you should) then the ExpectedException attribute has been deprecated.

You should instead use the following:

var exception = Assert.Throws<FileNotFoundException> (() => new MyFileType (nonExistingPath));
Assert.That (exception, Is.Not.Null);  // Or you can check for exception text...

No need to use a mock there. In fact, the mock does nothing interesting in your example.

Unit testing null parameter checks, We use constructor dependency injection throughout our application. void WhenSomethingIsNullConstructorThrowsNullException() { Assert. First, let's declare all mocks as private fields and create them in set-up method: as the validation of ArgumentNullException being thrown from constructors. Creating a Mock from an Existing Object¶ One problem with over use of mocking is that it couples your tests to the implementation of your mocks rather than your real code. Suppose you have a class that implements some_method. In a test for another class, you provide a mock of this object that also provides some_method.

If you tring to test MyFileType class, that it throws an exception if file does not exist, why you are creating mock. You code should be simple

[Test]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void MyFileType_CreationWithNonexistingPath_ExceptionThrown()
{
    // arrange
    var nonexistingPath = "C:\\does\\not\\exist\\file.ext";

    // act / assert
    var mock = new MyFileType(nonexistingPath);
}

MockFor (groovy 3.0.5 API), MockFor supports (typically unit) testing of classes in isolation by allowing a can mock all objects of a given class (or a single Groovy object); mocks even if static or calculated return values, throwing exceptions, asserting argument values , etc. The optional interceptConstruction flag allows mocking of constructor calls. Configure mock object to return the test data when the getAll() method of the UserService is invoked. Invoke an HTTP GET request to the /users URI. Validate if the response is correct. Verify that the HTTP status code is 200 (OK). Verify that the content-type of the response is application/json and its character set is UTF-8.

Throws Async | JustMock Documentation, Like Throws method, ThrowsAsync gives an option to pass arguments to the exception constructor. Assert.Throws returns the exception that's thrown which lets you assert on the exception. var ex = Assert.Throws<Exception>(() => user.MakeUserActive()); Assert.That(ex.Message, Is.EqualTo("Actual exception message")); So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws assertion will fail. However

Testing for Thrown Exceptions in xUnit.net, throw new InvalidOperationException( "Cannot read temperature before initializing. not thrown when the ReadCurrentTemperature method is called the test will fail. further asserts against the exception property values, for example: X.unit testing but one questions here can we mock static classes and� The following are top voted examples for showing how to use org.assertj.core.api.ThrowableAssert.ThrowingCallable.These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good example

JUnit Best Practices — Kyle Blaney, Aim for each unit test method to perform exactly one assertion strong assertions - verifying that vital dependent mock objects were interacted with correctly If a failure occurs during a test class constructor, an AssertionFailedError occurs and the stack We declare that the test method throws Exception rather than throws� Even if you set different constraints (different values for ->with() for example), the mock object will fail the test because at least one of the constraints won't be matched by the call. E.g. Even if you have multiple matchers, any of the calls should match all of the matchers' constraints.

Comments
  • I'm not certain this is directly related to your problem, but changing your string definition to using the @"" syntax is more readable and less error prone. For example, instead of String nonexistingPath = "C:\\does\\not\\exist\\file.ext"; you could simply put String nonexistingPath = @"C:\does\not\exist\file.ext";
  • Thank you for the tip. I've incorporated the change.
  • I am accepting this post as the answer since it does answer my original question.
  • I agree that my initial attempt at this problem had the code smell of a constructor doing too much work.
  • +1 for not throwing exceptions from a ctor. FxCop has a rule that will flag such code.
  • I am using the latest version of NUnit, so thank you for the heads up about the deprecation. In trying your solution, I encountered the same error as I did with alexanderb's solution -- cannot create an instance of of the abstract class 'MyFileType'.
  • Doesn't the fact that MyFileType is abstract prohibit me from using the 'new' operator as you have shown?
  • opps, sorry I missed that. Sure, you can't do 'new' there. But this also mean that you should not directly test this class, since it is abstract.. It has some behaviour, but this behaviour have to be tested on classes inherited from MyFileType. TDD, also could point to Desing issues. If something is hard to test, that 99% is design mistake. In you case, if class is abstract it is bad idea to put logic into constructor.