我在Visual Studio Ultimate 2010中使用Microsoft Moles并试图破坏Directory.Exists方法。我在程序集中有mscorlib.moles文件和以下标题行,但在尝试运行单元测试时仍然会得到MoleNotInstrumentedException。我之前使用过Microsoft Fakes,但我正在使用的项目让我们使用VS2010所以我必须使用Moles。我已将local.testsettings文件中的主机类型更改为Moles。任何人都知道为什么单元测试可能会抛出错误或出现问题?
using System.IO;
using System.IO.Moles;
using Microsoft.Moles.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[assembly: MoledAssembly("System.IO")]
[assembly: MoledType(typeof(System.IO.Directory))]
正在测试的简化方法失败。
private bool GetDirectoryExists(string directoryPath)
{
return Directory.Exists(directoryPath);
}
测试方法。
[TestMethod, TestCategory("Developer"), HostType("Moles")]
public void Test_MolesDirectoryExists()
{
string shouldBeValue = @"C:\Hello\Nope\Not Here";
string returnedValue = null;
using (MolesContext.Create())
{
MDirectory.ExistsString = s =>
{
Trace.WriteLine("Passed in value: " + s);
returnedValue = s;
return true;
};
bool result = this.GetDirectoryExists(shouldBeValue);
Trace.WriteLine("DirectoryExists: " + result);
Assert.IsTrue(result, "Directory does not exist.");
Assert.AreEqual(shouldBeValue, returnedValue, "Path values do not match");
}
}
异常错误消息
Test method TempUsersService.Tests.TempUsersTests.Test_ShimDirectoryExists threw exception:
Microsoft.Moles.Framework.Moles.MoleNotInstrumentedException: The System.Boolean
System.IO.Directory.Exists(System.String path) was not instrumented
To resolve this issue, add the following attribute in the test project:
using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.IO.Directory))]
异常堆栈跟踪
Microsoft.ExtendedReflection.Monitoring._Detours.InvokeEvent[T](T value, SafeAction`1 eh)
Microsoft.ExtendedReflection.Monitoring._Detours.OnAttachedUninstrumentedMethod(Method method)
Microsoft.ExtendedReflection.Monitoring._Detours.CheckInstrumentation(Method method)
Microsoft.ExtendedReflection.Monitoring._Detours.AttachDetour(Object _receiver, Method method, Delegate detourDelegate)
Microsoft.Moles.Framework.Moles.MoleRuntime.SetMoleMethod(Delegate _stub, Object _receiver, Method method)
Microsoft.Moles.Framework.Moles.MoleRuntime.SetMole(Delegate _stub, Type receiverType, Object _receiver, String name, MoleBindingFlags flags, Type[] parameterTypes)
Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicStatic(Delegate _stub, Type receiverType, String name, Type[] parameterTypes)
System.IO.Moles.MDirectory.set_ExistsString(Func`2 value) in c:\Users\abc123\Desktop\workspace\Project\Tests\TempUsersService.Tests\obj\x86\Debug\Moles\m\m.g.cs: line 0
TempUsersService.Tests.TempUsersTests.Test_ShimDirectoryExists() in C:\Users\abc123\Desktop\workspace\Project\Tests\TempUsersService.Tests\TempUsersTests.cs: line 401
答案 0 :(得分:1)
问题在于
的行[assembly: MoledType(typeof(System.IO.Directory))]
在命名空间内。这导致编译器无法看到该行,因此抛出了MoleNotInstrumentedException。解决方案是将此行移到命名空间之外。一旦我这样做,所有使用Moles主机的单元测试都开始正常工作。