How to mock property with NUnit?

How do I make fun of a property using NUnit?


NOTE : I found this peripheral mocking answer to be extremely useful and repurpose it as a separate question and write answer for others to find.

Other answers are welcome.

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

+7
source share
1 answer

To make fun of 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 Property

 using NUnit.Mocks; 

In NUnit, a property name can be mocked with get_PropertyName to mock get accessor and set_PropertyName to mock a set accessory using the mock Expect * (..) library:

 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 example above, the .Names property is mocked as get_Names or set_Names .


Etc.

This blog post provides additional information, given that NUnit seems to provide mock methods only for target methods:

I began to think about it and realized that setters are simply perceived as special named methods under covers

+9
source

All Articles