Question

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.

Was it helpful?

Solution 2

OTHER TIPS

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]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top