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

2 posts, 0 answers
  1. Lee Saunders
    Lee Saunders avatar
    20 posts
    Member since:
    Jul 2009

    Posted 24 Apr 2013 Link to this post

    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




  2. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 26 Apr 2013 Link to this post

    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.
  3. DevCraft R3 2016 release webinar banner
Back to Top