Link to home
Start Free TrialLog in
Avatar of dyarosh
dyarosh

asked on

how to assert for any IOException in mstest unit testing c#

I have a unit test that is testing that an IOException is thrown if a file is not found.  I set the test up as follows:

        [TestMethod]
        [ExpectedException(typeof(IOException))]
        public void Throws_Error_When_XMLFileName_Is_Not_Found()
        {
            // Arrange
            var mockHttpContextBase = new Mock<HttpContextBase>();
            var mockHttpServerUtilityBase = new Mock<HttpServerUtilityBase>();
            mockHttpContextBase.Setup(x => x.Server).Returns(mockHttpServerUtilityBase.Object);
            mockHttpServerUtilityBase.Setup(server => server.MapPath(It.IsAny<string>())).Returns(@"C:\SomeDirectory\SomeFile.XML");

            // Act
            LoadServerEnvironmentsFromXML sut = new LoadServerEnvironmentsFromXML(mockHttpContextBase.Object);
            sut.LoadServerList("SomeFile.xml");

            // Assert
            // An exception should be thrown and test will fail if it doesn't
        }

Open in new window


I don't care if it throws a DirectoryNotFoundException or FileNotFoundException.  How do I test for that?  Right now the test fails because it says a DirectoryNotFoundException was thrown.

Thanks for any suggestions!
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dyarosh
dyarosh

ASKER

Thank you.  I was hoping there was a way to catch a general IO Exception but I will use your solution.