Create Reusable Mock of FileInfo and other Core Classes

2 posts, 0 answers
  1. Kevin
    Kevin avatar
    3 posts
    Member since:
    Mar 2012

    Posted 16 Oct 2012 Link to this post

    I have determined that the following works:

    public class TestCase1
    {
        static TestCase1()
        {
            Mock.Replace<FileInfo, bool>(x => x.Exists).In<TestCase1>();
        }
     
        [Theory]
        [InlineData(false)]
        [InlineData(true)]
        public void MockedFileExists(bool expected)
        {
            FileInfo file = Helper.GetMockedFile(expected);
     
            bool actual = file.Exists;
     
            Assert.Equal(expected, actual);
        }
    }
     
    public class TestCase2
    {
        static TestCase2()
        {
            Mock.Replace<FileInfo, bool>(x => x.Exists).In<TestCase2>();
        }
     
        [Theory]
        [InlineData(false)]
        [InlineData(true)]
        public void MockedFileExists(bool expected)
        {
            FileInfo file = Helper.GetMockedFile(expected);
     
            bool actual = file.Exists;
     
            Assert.Equal(expected, actual);
        }
    }
     
    public class Helper
    {
        public static FileInfo GetMockedFile(bool exists)
        {
            FileInfo file = Mock.Create<FileInfo>("c:\\test.jpg");
            Mock.Arrange(() => file.Exists).Returns(exists);
            return file;
        }
    }

    I have two questions regarding the previous code:

    1. Is there a way I can specify the Mock.Replace once and not have to specify it in every code file I use the helper method?
    2. WIth this approach I have to add a Mock.Replace method for each method that I want to mock.  in cases where I am mocking multiple method calls is there a way to avoid having to specify a Mock.Replace for each method?
  2. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 19 Oct 2012 Link to this post

    Hello Kevin,

     Thank you for contacting Telerik support.

     As I can understand you would like to initialize the Mock.Replace<T> on assembly level. Unfortunately this is not supported in JustMock, because it is a performance blocker in most cases. In JustMock "Mock.Replace" is class based and as such you must initialize it on class level.

     I would recommend you grouping the test methods, that requires MSCorlib mocking into one class, if possible. This will save you a lot of execution time and also you won`t have to write the initialization for every test method you have.

     I hope this answers your question. If there is anything else I can help you with, do not hesitate to ask.

    Kind regards,
    Kaloyan
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Back to Top