Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a property using NUnit?

How do I mock a property using NUnit?


NOTE: I found this peripheral mocking answer to be extremely useful and repurposed it as a distinct question and answer entry here for others to find.

Other answers welcome too.

NUnit-Discuss Note: NUnit Mocks was created over a weekend as a toy mock implementation [...] I'm beginning to think that was a mistake, because you are far from the first person to become reliant on it.
-- http://groups.google.com/group/nunit-discuss/msg/55f5e59094e536dc
(Charlie Pool on NUnit Mocks)

like image 890
John K Avatar asked Mar 16 '11 20:03

John K


Video Answer


1 Answers

To mock the Names property in the following example...

Interface IView {    
    List<string> Names {get; set;} 
}

public class Presenter {    
    public List<string> GetNames(IView view)    {
       return view.Names;    
    } 
}

NUnit Mock Solution for a Property

using NUnit.Mocks;

In NUnit a PropertyName can be mocked with get_PropertyName to mock the get accessor and set_PropertyName to mock the set accessor, using the mock library's Expect*(..) methods like so:

List names = new List {"Test", "Test1"};
DynamicMock mockView = new DynamicMock(typeof(IView));

mockView.ExpectAndReturn("get_Names", names);

IView view = (IView)mockView.MockInstance;
Assert.AreEqual(names, presenter.GetNames(view));

Therefore, in our specific code sample at the top, the .Names property is mocked as either get_Names or set_Names.


Etc.

This blog post provides additional insight considering NUnit seemingly provides mock methods to only target methods:

I started thinking about it and realized that Property getters and setters are just treated as speciallly named methods under the covers

like image 169
John K Avatar answered Nov 15 '22 10:11

John K