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

How to mock the constructor of a mscorlib class?

1 Answer 19 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Gustavo
Top achievements
Rank 1
Gustavo asked on 04 Jun 2013, 04:24 AM

Hi,

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.

Thanks,
Gustavo

public class MyClass
{
   public static string DoSomething(string pathToFile)
 
   {
 
       TextReader xmlTextReader = new StreamReader(pathToFile);
 
       //some method logic
 
      //returns a string
 
   }
 
}

1 Answer, 1 is accepted

Sort by
0
Kaloyan
Telerik team
answered on 05 Jun 2013, 11:17 AM
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.

Regards,
Kaloyan
Telerik
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
Gustavo
Top achievements
Rank 1
Answers by
Kaloyan
Telerik team
Share this question
or