Hi Jimmy
I'm very new to TypeMock.
Welcome :-)
I want to mock the ConfigurationSettings.AppSettings so that it always returns a specified string. Unfortunately, the test always fails with TypeMock.TypeMockException : No method AppSettings in type System.Configuration.ConfigurationSettings returns System.String"
I've looked in the framework documentation and I found that AppSettings returns a NameValueCollection and not a string. Is that why the tests are failing? Is there any other way? Thanks a lot for any help. :D
You are correct! you are trying to return a string instead of a NameValueCollection. This won't work.
There are a few ways to mock this scenario. As follows
1. Mock NameValueCollection
2. Create your own NameValueCollection and mock ConfigurationSettings.AppSettings to return it
3. Create a mocked NameValueCollection and mock ConfigurationSettings.AppSettings to return it
Here are the examples returning "TypeMock":
:arrow: 1. Mock NameValueCollection - Note: We are mocking an Index
Dim valueCollectionMock As Mock = MockManager.Mock(GetType(NameValueCollection))
valueCollectionMock.ExpectGetIndexAlways("TypeMock")
:arrow: 2. Create your own NameValueCollection and mock ConfigurationSettings.AppSettings to return it
- Note: AppSettings is a property
' Create our own NameValueCollection
Dim valueCollection As NameValueCollection = New NameValueCollection
valueCollection("expectedKey") = "TypeMock"
' AppSettings should return our collection
Dim appSettingsMock As Mock = MockManager.Mock(GetType(ConfigurationSettings))
appSettingsMock.ExpectGetAlways("AppSettings",valueCollection)
:arrow: 3. Create a mocked NameValueCollection and mock ConfigurationSettings.AppSettings to return it
' Create our own mocked NameValueCollection
' We use MockObject as we need the actual instance
Dim valueCollectionMock As Mock = MockManager.MockObject(GetType(NameValueCollection))
valueCollectionMock.ExpectGetIndexAlways("TypeMock")
' Get the actual instance
Dim valueCollection As NameValueCollection = valueCollectionMock.Object
' AppSettings should return our collection
Dim appSettingsMock As Mock = MockManager.Mock(GetType(ConfigurationSettings))
appSettingsMock.ExpectGetAlways("AppSettings",valueCollection)
Each method has its own advantages.
:idea: Method 1. Is the easiest although if NameValueCollection is used in other places we will get strange results.
:idea: Method 2. Is a bit better, but we have to know the exact names of keys that we expect to have (This is not such a bad resriction but you need to return the same string for all keys..)
:idea: Method 3. Is a combination of 1 & 2. We mock NameValueCollection but use it only in our context
Hope this helps