待测试组件中:
namespace MyApp.Workers
{
internal interface IWork { void DoWork() }
internal class RealWork : IWork { public void DoWork() { /* impl omitted */ } }
}
namespace MyApp.Helpers
{
internal static class ClassFetcher
{
public static Type GetWorkClass(string className)
{
string qualifiedClassName = typeof(IWork).Namespace + "." + className;
cls = Type.GetType(qualifiedClassName);
if (cls == null)
throw new Exception($"Can't find class \"{className}\".");
if (!typeof(IWork).IsAssignableFrom(cls))
throw new Exception($"The class \"{className}\" doesn't implement IWork.");
}
}
}
在测试组件中:
// Usings omitted...
namespace MyApp.Workers
{
// Class that does implement IWork.
public class TestWork : IWork { public void DoWork() {} }
// Class that does not implement IWork.
public class TestNoWork { }
}
namespace MyApp_Test.Helpers
{
[TestClass]
public class UnitTestClassFetcher
{
[TestMethod]
public void FindsWorkClass()
{
ClassFetcher.GetWorkClass("TestWork");
}
[TestMethod]
public void DoesNotAcceptNoWorkClass()
{
ClassFetcher.GetWorkClass("TestNoWork");
}
}
}
上
GetWorkClass
Type.GetType(...)
呼叫内部
GetWorkClass公司
返回null。如果我通过
"RealWork"
从测试方法来看,它是有效的。
那么,我如何启用
欢迎有无第三方框架、工具和插件的建议。
根据@LasseV的评论。Karlsen和@dymanoid的标记答案,我只是改变了测试方法的代码如下:
[TestMethod]
public void FindsWorkClass()
{
string namespace = typeof(IWork).Namespace;
string className = typeof(TestWork).AssemblyQualifiedName.Substring(namespace.Length + 1);
ClassFetcher.GetWorkClass(className);
}