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

Create Reusable Mock of FileInfo and other Core Classes

1 Answer 88 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Kevin
Top achievements
Rank 1
Kevin asked on 16 Oct 2012, 08:08 PM
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?

1 Answer, 1 is accepted

Sort by
0
Kaloyan
Telerik team
answered on 19 Oct 2012, 02:50 PM
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.

Tags
General Discussions
Asked by
Kevin
Top achievements
Rank 1
Answers by
Kaloyan
Telerik team
Share this question
or