This is a migrated thread and some comments may be shown as answers.

How do you mock a static method that has a mscorlib method you want to mock

1 Answer 27 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Lee Saunders
Top achievements
Rank 1
Lee Saunders asked on 24 Apr 2013, 06:51 PM
Hello,

I need to mock the DateTime.Now static method in mscorlib.  I've got it to work if it is in a non-static class.

(EXAMPLE CLASS)
class Program
{
    static void Main()
    {
        var results = new Program().CheckForY2K();
 
        Console.WriteLine(results);
        Console.Read();
    }
 
    internal bool CheckForY2K()
    {
        return DateTime.Now == new DateTime(2000, 1, 1);
    }
}

(EXAMPLE WORKING TEST)
[TestFixture]
public class NuintTest
{
   static NuintTest()
    {
        Mock.Replace(() => DateTime.Now).In<Program>(x => x.CheckForY2K());
    }
 
    [Test]
    public void TestY2K()
    {
        Mock.Arrange(() => DateTime.Now).Returns(new DateTime(2000, 1, 1));
        var results = new Program().CheckForY2K();
        Assert.IsTrue(results);
    }
}

But, I need it to work on static class

(ANOTHER EXAMPLE)
class Program
{
    static void Main()
    {
        var results = CheckForY2K();
 
        Console.WriteLine(results);
        Console.Read();
    }
 
    internal static bool CheckForY2K()
    {
        return DateTime.Now == new DateTime(2000, 1, 1);
    }
}

But this time, JustMock complains:
Mock.Replace(() => DateTime.Now).In<Program>(x => x.CheckForY2K());

That it cannot access static method "CheckForY2K" in non-static context.

What would the correct syntax be?  I cannot find an example.

Lee




1 Answer, 1 is accepted

Sort by
0
Kaloyan
Telerik team
answered on 26 Apr 2013, 07:00 AM
Hello Lee,

Thank you for the question.

If the method you arrange mscorlib mocking against is static (or non-public), you can use Mock.Replace() for its class. For your scenario, I made the following example and it works as expected:
static JustMockTest1()
{
    Mock.Replace(() => DateTime.Now).In<Program>();
}
 
[Test]
public void TestY2K2()
{
    Mock.Arrange(() => DateTime.Now).Returns(new DateTime(2000, 1, 1));
    var results = Program.CheckForY2K();
    Assert.IsTrue(results);
}

I hope this helps.

All the best,
Kaloyan
the Telerik team
Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums, or our JustTrace or JustMock portals.
Tags
General Discussions
Asked by
Lee Saunders
Top achievements
Rank 1
Answers by
Kaloyan
Telerik team
Share this question
or