How to use Expected Exception attribute in Visual Studio Unit Testing
-
Friday, August 17, 2012 4:48 AM
Hi friends,
I'm new to Visual Studio 2010 Unit Testing. i have a doubt with ExpectedException attribute. i have given my scenario below
I have a main class which contains getMyName method,
public partial class MainWindow : Window { public string getMyName(myClass process) { return process.MyName; } }This is the class definition for parameter
myClass.cs :
------------public class myClass { string myName; public string MyName { get { return myName; } set { myName = value; } } }
My Test Method :
----------------------[TestMethod()] [ExpectedException(typeof(System.NullReferenceException))] public void getMyNameTest() { MainWindow target = new MainWindow(); myClass process = null; string expected = "hi"; string actual = target.getMyName(process); // i'm getting NullReferenceException Here since not created instance for myClass Assert.AreSame(expected, actual); }
When i execute this Test method i'm getting NullReferenceException in getMyName(process) line though i have given this as Expected Exception.Could you Please tell me ,my understanding is correct or not and how it behaves ?
Thanks - Ravi
All Replies
-
Friday, August 17, 2012 8:51 AMModerator
HI Ravi,
Thank you for posting in the MSDN forum.
According to your scenario above, you use the Expected Exception attribute correctly.
But using Expected Exception attribute is not related to that whether you will get the expected exception or not.
You will always get theNullReferenceException exception when you execute the test method just because of your code “myClass process=null”.
Using Expected Exception attribute means that theNullReferenceException exception is expected during test method execution. If the NullReferenceException exception is thrown, your unit test will pass. Otherwise your test will fail.
I hope this will be helpful to you.
Best regards,
Amanda Zhu [MSFT]
MSDN Community Support | Feedback to us
- Marked As Answer by Amanda ZhuMicrosoft Contingent Staff, Moderator Tuesday, August 28, 2012 2:56 AM

