Nmock Gotcha about Reference Parameters
Published on
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:
public bool TrySetSummaryContent(string content, out Exception raisedError){ raisedError = null;
try { webBrowser.DocumentText = content; } catch (Exception ex) { raisedError = ex; return false; }
return true;}
This method is called by the presenter method below:
bool ContentSet(string _summaryContent) {
// This loop is used to try setting the content of the view 3 times before erroring out. int SetContentAttempt = 0; Exception exRaised; do { if (View.TrySetSummaryContent(_summaryContent, out exRaised)) { return true; } SetContentAttempt++; } while (SetContentAttempt<> LogError(exRaised, "The retention reason summary could not be displayed", "Summary Unavailable","Web Browser control raised an exception.");
return false;}
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:
string op = "Test Content"; Expect.Once .On(_mockView) .Method("TrySetSummaryContent") .With(Is.EqualTo(op), Is.Out) .Will(new SetNamedParameterAction("raisedError", new Exception()), Return.Value(true));