Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking ConfigurationManager.AppSettings with JustMock

Tags:

c#

justmock

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.

like image 945
joelnet Avatar asked May 26 '26 05:05

joelnet


1 Answers

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]

like image 75
Mehfuz Avatar answered May 28 '26 09:05

Mehfuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!