How can you mock a property of type NameValueCollection?

953 views
Skip to first unread message

mts...@gmail.com

unread,
Jan 23, 2009, 4:35:32 PM1/23/09
to Moq Discussions
Is it possible to mock the following property?

public NameValueCollection AppSettings {get;}

with something like:

mock.Expect(s => s.AppSettings["TestKey"]).Returns("TestValue");

Daniel Cazzulino

unread,
Jan 23, 2009, 6:07:35 PM1/23/09
to moq...@googlegroups.com

First it would have to be virtual.
Next, you could just have a new collection returned, which you populate as needed.

andreister

unread,
Jan 24, 2009, 10:25:52 AM1/24/09
to Moq Discussions
As Daniel mentioned, you need to make the property virtual.

Next, as soon as NameValueCollection indexer is not virtual, Moq
cannot mock it so it's not possible to mock it in a way you want.

However, getter/setter of NameValueCollection ARE virtual, so you can
use that:

var foo = new Mock<Foo>();
foo.Setup(x => x.AppSettings.Get("foo")).Returns("bar");
Assert.Equal("bar", foo.Object.AppSettings.Get("foo"));

(Note, that starting from Moq 3.0 "Expect" is is renamed to "Setup")

Or, as Daniel suggested, you can mock the whole collection, not just
one key/value.

mts...@gmail.com

unread,
Jan 26, 2009, 12:39:21 PM1/26/09
to Moq Discussions
I'm actually trying to mock System.Configuration.ConfigurationManger
so I created a wrapper

public interface IConfigurationManager
{
NameValueCollection AppSettings {get;}
ConnectionStringSettingsCollection ConnectionStrings {get;}
object GetSection (string sectionName);
}

I've subclassed ConfigurationManager to add extra functionality which
is why I wanted to Mock the AppSettings collection.

So using the following worked out perfectly

var configurationManager = new Mock<IConfigurationManager> ();
configurationManager.Expect (s => s.AppSettings.Get
("TestKey.Local")).Returns ("LocalValue");
configurationManager.Expect (s => s.AppSettings.Get
("TestKey.Development")).Returns ("DevelopmentValue");
configurationManager.Expect (s => s.AppSettings.Get
("TestKey")).Returns ("DefaultValue");

_configManager = new ConfigManager (configurationManager.Object,
ENVIRONMENT_TOKEN);

When AppSettings["TestKey"] gets called I get the expected value (ie
DefaultValue).

thank you

Daniel Cazzulino

unread,
Jan 26, 2009, 1:33:30 PM1/26/09
to moq...@googlegroups.com
very cool :)
--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471
Reply all
Reply to author
Forward
0 new messages