Moq: test to see if exception is thrown


/ Published in: C#
Save to your folder(s)

The ExpectedException section under [TestMethod] is where you tell Moq what type of exception your listening for. If that exception is thrown, then this test will pass and it will stop running all the code under the target.CalculateProvisionalPrice.

In case the exception isn't thrown, the Assert.Fail will throw an exception alerting you that the ArgumentNullException wasn't thrown.


Copy this code and paste it in your HTML
  1. [TestMethod]
  2. [ExpectedException(typeof(ArgumentNullException))]
  3. public void PricingService_CalculateProvisionalPrice_NullReference_Test()
  4. {
  5. // Action
  6. target.CalculateProvisionalPrice(null);
  7.  
  8. Assert.Fail("Should have thrown ArgumentNullException");
  9. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.