Tell don't ask

January 15, 2008

Nmock Gotcha about Reference Parameters

Filed under: Gotchas,NMock — telldontask @ 11:04 am


I wrote a method in a view that cause me no end of grief when testing its presenter the other day.

I’ll elaborate on this a little more when I get the time but for now, here are the bones of the issue:

  1. public bool TrySetSummaryContent(string content, out Exception raisedError)
  2.         {
  3.             raisedError = null;
  4.             try
  5.             {
  6.                 webBrowser.DocumentText = content;
  7.             }
  8.             catch (Exception ex)
  9.             {
  10.                 raisedError = ex;
  11.                 return false;
  12.             }
  13.             return true;
  14.         }

This method is called by the presenter method below:

  1. bool ContentSet(string _summaryContent)
  2. {
  3.     // This loop is used to try setting the content of the view 3 times before erroring out.
  4.     int SetContentAttempt = 0;
  5.     Exception exRaised;
  6.     do
  7.     {
  8.         if (View.TrySetSummaryContent(_summaryContent, out exRaised))
  9.         {
  10.             return true;
  11.         }
  12.         SetContentAttempt++;
  13.     } while (SetContentAttempt<> LogError(exRaised, "The retention reason summary could not be displayed", "Summary Unavailable","Web Browser control raised an exception.");
  14.     return false;
  15. }

To write a unit test for the Content Set Method, I mocked out the view object and had to stipulate not only that the method would return a true or false value but I also had to state that the raisedError exception object in the TrySetSummaryContent method will be instantiated as so:

  1. string op = "Test Content";
  2.             Expect.Once
  3.             .On(_mockView)
  4.             .Method("TrySetSummaryContent")
  5.             .With(Is.EqualTo(op), Is.Out)
  6.             .Will(new SetNamedParameterAction("raisedError", new Exception()), Return.Value(true));

1 Comment »

  1. Thanks for the post! Saved my day from figuring this magic out.

    Comment by Kenneth Xu — July 4, 2008 @ 7:30 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: