3

Following the directions at: http://www.telerik.com/help/justmock/advanced-usage-static-mocking.html

I'm unsuccessful in mocking ConfigurationManager.AppSettings. Here's the code I'm using...

[TestMethod]
public void my_test()
{
    // Arrange
    var appSettings = new NameValueCollection {
        { "test1", "one" }
    };

    Mock.Arrange(() => ConfigurationManager.AppSettings)
        .Returns(appSettings)
        .MustBeCalled();

    // Act
    var test1 = ConfigurationManager.AppSettings["test1"];

    // Assert
    Assert.AreEqual("one", test1);
}

This is the error I receive.

Assert.AreEqual failed. Expected:. Actual:<(null)>.

Is it possible to mock this object?

[edit] I'm also using the Trial.

joelnet
  • 13,621
  • 5
  • 35
  • 49

2 Answers2

3

I just tried your test and it worked as expected:

// Arrange 
var appSettings = new NameValueCollection { { "test1", "one" } };

Mock.Arrange(() => ConfigurationManager.AppSettings)
    .Returns(appSettings)
    .MustBeCalled();

// Act 
var test1 = ConfigurationManager.AppSettings["test1"];

// Assert 
Assert.AreEqual("one", test1);

Here please make sure that Configuration.AppSettings is not already invoked in some static constructor of your project.

Here to note that .net profiler intercepts during OnJITCompilationStarted and this fires only once for a given member.

Moreover, please make sure that your profiler is configured properly and JM plugin for VS is installed. You can check if the profiler is enabled by Mock.IsProfilerEnabled.

Finally, you generally dont need to use Mock.SetupStatic(#TARGET_TYPE#), unless you are doing strict mock or want to fake static constructor for a given type. When you will be doing Mock.Arrange, it will automatically set the interceptors if not already.

[Note: I used the latest version]

Mehfuz
  • 325
  • 2
  • 8
  • Strange, I still can't get it to work. Maybe there is a limitation in the trial? I created a fresh JustMock Test project directly from the template and I still can't get it to pass. I even added this (which passes) Assert.IsTrue(Mock.IsProfilerEnabled); – joelnet Dec 13 '11 at 19:52
0

source: http://www.telerik.com/community/forums/justmock/general-discussions/problems-mocking-the-configurationmanager-appsettings.aspx

Official response is, this appears to be an issue with MSTest only.

joelnet
  • 13,621
  • 5
  • 35
  • 49