I want to replace behavior of Environment.GetFolderPath
in my unittest, but after generation moles for System
assembly, System.Moles
assembly does not contain definition of type MEnvironment
.

- 316
- 1
- 7
1 Answers
Have you tried stubbing in an interface type? The sub can be passed in via constructor injection or via method input parameter. For example, create interface IEnvironment, including the GetFolderPath method. If you already know how to do this, then feel free to go on your way. Otherwise, the following demonstrates how to stub in the Environment class. (I am typing this on my phone, so bear with me ;)
public interface IEnvironment
{
string GetFolderPath(Environment.SpecialFolder folder);
}
Next, create a stub:
public class MyEnvironment : Environment, IEnvironment
{
public string GetFolderPath(Environment.SpecialFolder folder)
{
return base.GetFolderPath(folder);
}
}
Pass the stub in to your method or class constructor as a parameter:
public void MyMethod(IEnvironment env)
{
var path = env.GetFolderPath():
}
For testing, create a mock type, or mole MyEnvironment.GetGolderPath. Creating a mock is preferable to a moled type, for performance reasons. The mock simply returns a value instead of calling the base method, just as the moled type would. He stub is necessary, either way, so you may as well make the mock, as it can be reused for other tests.

- 1,526
- 1
- 15
- 27
-
But my production code don't have ability to set Environment instance . It can be done without Moles, use Moq or anything else. – Eduard Kibort Aug 18 '11 at 15:03
-
I don't expect that your code already stub the Environment class, which is why I recommend refactoring one in. And, yes, it certainly can and should be done without Moles. The purpose of the stub is to provide means of passing the mock type to the code-in-test. – Mike Christian Aug 18 '11 at 16:42