开发者

Can't create Mole for System.Environment class

I want to replace behavior of Environment.GetFo开发者_开发百科lderPath in my unittest, but after generation moles for System assembly, System.Moles assembly does not contain definition of type MEnvironment.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜