code_junkie

How can I test for an expected exception with a specific exception message from a resource file in Visual Studio Test?

Nov 11th, 2011
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. [TestMethod]
  2. [ExpectedException(typeof(CriticalException))]
  3. public void GetOrganisation_MultipleOrganisations_ThrowsException()
  4.  
  5. [TestMethod]
  6. [ExpectedException(typeof(CriticalException), "An error occured")]
  7. public void GetOrganisation_MultipleOrganisations_ThrowsException()
  8.  
  9. [TestMethod]
  10. [ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)]
  11. public void GetOrganisation_MultipleOrganisations_ThrowsException()
  12.  
  13. public static class ExceptionAssert
  14. {
  15. public static T Throws<T>(Action action) where T : Exception
  16. {
  17. try
  18. {
  19. action();
  20. }
  21. catch (T ex)
  22. {
  23. return ex;
  24. }
  25. Assert.Fail("Exception of type {0} should be thrown.", typeof(T));
  26.  
  27. // The compiler doesn't know that Assert.Fail
  28. // will always throw an exception
  29. return null;
  30. }
  31. }
  32.  
  33. [TestMethod]
  34. public void GetOrganisation_MultipleOrganisations_ThrowsException()
  35. {
  36. OrganizationList organizations = new Organizations();
  37. organizations.Add(new Organization());
  38. organizations.Add(new Organization());
  39.  
  40. var ex = ExceptionAssert.Throws<CriticalException>(
  41. () => organizations.GetOrganization());
  42. Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);
  43. }
  44.  
  45. [Fact]
  46. public void TestException()
  47. {
  48. Exception ex = Record.Exception(() => myClass.DoSomethingExceptional());
  49. // Assert whatever you like about the exception here.
  50. }
  51.  
  52. [ExpectedException( Handler="HandlerMethod" )]
  53. public void TestMethod()
  54. {
  55. ...
  56. }
  57.  
  58. public void HandlerMethod( System.Exception ex )
  59. {
  60. ...
  61. }
Add Comment
Please, Sign In to add comment