Exception in MS Unit Test?

I created a unit test for my project method. This method throws an exception when the file is not found. I wrote a unit test for this, but I still cannot pass the test when an exception occurs.

Method

public string[] GetBuildMachineNames(string path) { string[] machineNames = null; XDocument doc = XDocument.Load(path); foreach (XElement child in doc.Root.Elements("buildMachines")) { int i = 0; XAttribute attribute = child.Attribute("machine"); machineNames[i] = attribute.Value; } return machineNames; } 

Unit test

 [TestMethod] [DeploymentItem("TestData\\BuildMachineNoNames.xml")] [ExpectedException(typeof(FileNotFoundException),"Raise exception when file not found")] public void VerifyBuildMachineNamesIfFileNotPresent() { var configReaderNoFile = new ConfigReader(); var names = configReaderNoFile.GetBuildMachineNames("BuildMachineNoNames.xml"); } 

Should I handle the exception in the method or am I missing something else?

EDIT:

The path I pass is not the one to find the file, so this test should pass ... that is, if the file does not exist in that path.

+4
source share
3 answers

In your unit test, it seems that you are deploying an xml file: TestData\BuildMachineNoNames.xml , which you pass to GetBuildMachineNames . Thus, the file exists, and you cannot expect a FileNotFoundException be FileNotFoundException . So maybe like this:

 [TestMethod] [ExpectedException(typeof(FileNotFoundException), "Raise exception when file not found")] public void VerifyBuildMachineNamesIfFileNotPresent() { var configReaderNoFile = new ConfigReader(); var names = configReaderNoFile.GetBuildMachineNames("unexistent.xml"); } 
+6
source

By setting [ExpectedException (typeof (FileNotFoundException), attribute "Raise exception when file is not found")], you expect the method to throw a FileNotFoundException if a FileNotFoundException is not thrown. Otherwise, the test will succeed.

+1
source

I never understood the meaning of ExpectedException . You should only be able to exclude code, not attributes. This is a more effective practice, and also allows you to do things after raising it (for example, more checks) ... It will also allow you to stop the code in the debugger and check everything, rather than asking in the forums. :)

I would use Assert.Throws (TestDelegate code) ;.
See here for an example .

0
source

Source: https://habr.com/ru/post/1338404/


All Articles