How to mock the constructor of a mscorlib class?

2 posts, 0 answers
  1. Gustavo
    Gustavo avatar
    3 posts
    Member since:
    May 2013

    Posted 03 Jun 2013 Link to this post


    I want to mock the StreamReader constructor below so the unit test can pass that statement without failing. All the samples of mocking mscorlib relies on mocking a method, but I want to mock the constructor, how do I do that?

    I don't want to create a valid file and pass a valid pathToFile.

    We are currently using version 2013.1.507, please provide a sample that works on this version.


    public class MyClass
       public static string DoSomething(string pathToFile)
           TextReader xmlTextReader = new StreamReader(pathToFile);
           //some method logic
          //returns a string
  2. Kaloyan
    Kaloyan avatar
    880 posts

    Posted 05 Jun 2013 Link to this post

    Hello Gustavo,

    Unfortunately, this is not possible with JustMock 2013.1.507.

    A possible solution is to extract the construction of your "xmlTextReader" into another method, like this:
    public static TextReader MyXMLTextReader(string pathToFile)
        TextReader xmlTextReader = new StreamReader(pathToFile);
        return xmlTextReader;
    public static string DoSomething(string pathToFile)
        TextReader xmlTextReader = MyXMLTextReader(pathToFile);
        //some method logic
        //returns a string
    Then, you will be able to arrange against "MyXMLTextReader" method:
    Mock.Arrange(() => MyClass.MyXMLTextReader(Arg.AnyString)).DoNothing();
    Note, you could also arrange its return value as desired. Finally, you will be able to call the "DoSomething" method no matter the string passed as argument.

    However, in the latest internal builds we have included the Future Constructor Mocking feature. This will let you future mock the constructor of an instance (even to a MsCorlib member), the following way:
    Mock.Arrange(() => new StreamReader(Arg.AnyString)).DoNothing();
    With this approach, no refactoring to your existing system under test will be necessary.

    I hope this helps.

    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.
Back to Top