Search code examples
c#unit-testingexceptionmstestargumentnullexception

MSTest Unit Test asserting specific exception messages


I'm writing my first Unit test for very small project. Here the expected result and result both return a ArgumentNullException but the test still fails. Any idea why?

        [TestMethod]
        public void InsertFileBeginning_FilePathNull_ReturnArgumentNullException()
        {
            // Arrange
            var generateFile = new GenerateFile();
            string parameter = null; //pass FilePath Null

            var expectedExcetpion = new ArgumentNullException();

            // Act & Assert
            var result = Assert.ThrowsException<ArgumentNullException>(() => generateFile.InsertFileBeginning(parameter));
            Assert.AreEqual(expectedExcetpion, result);

        }

------InsertFileBeginning function--------

public void InsertFileBeginning(string filePath)
        {
            try
            {
                using (var fs = new FileStream(filePath, FileMode.Create))
                {
                    Byte[] metadata = new UTF8Encoding(true).GetBytes("THis is a test content");
                    fs.Write(metadata, 0, metadata.Length);

                }
            }
            catch (Exception exception)
            {
                throw exception;
            }

        }

Error:

Expected: System.ArgumentNullException: Value cannot be null.

Actual: System.ArgumentNullException: Path cannot be null. Parameter name: path

Message: Assert.AreEqual failed. Expected:<System.ArgumentNullException: Value cannot be null.>. Actual:<System.ArgumentNullException: Path cannot be null.
Parameter name: path
   at SmartTestSelecter.GenerateFile.InsertFileBeginning(String filePath) in C:\Users\CC\SmartTestSelecter\GenerateFile.cs:line 31
   at SmartTestSelecterUnitTests.GenerateFileTest.<>c__DisplayClass0_0.<InsertFileBeginning_FilePathNull_ReturnArgumentNullException>b__0() in C:\Users\CC\STSUnitTests\GenerateFileTest.cs:line 21
   at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsException[T](Action action, String message, Object[] parameters)>. 

Solution

  • Look at this;

    var expectedException = new ArgumentNullException();
    // Act & Assert
    var result = Assert.ThrowsException<ArgumentNullException>(() => generateFile.InsertFileBeginning(parameter));
    Assert.AreEqual(expectedException, result);
    

    expectedException is an Object of type ArgumentNullException and result is also an object of type ArgumentNullException - however they're not the same object! you have 2 instances of the same type.

    Now AreEqual(..) uses .Equals from what i could gather online.

    I think that you're comparing the references of expectedException with result here. They are of course not the same. What you should instead do (if my assumptions are right) is check if the result is of the same type, rather than use AreEqual(..).

    It seems you can use this method for that: Assert.IsInstanceOfType https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.isinstanceoftype?view=mstest-net-1.2.0

    e.g.:

    Assert.IsInstanceOfType(result, typeof(ArgumentNullException));