[英]How to test a method that uses Activator.CreateInstance(…)?
I'm writing a test for the following method: 我正在为以下方法编写测试:
public IAnInterface Instantiator()
{
var type = Type.GetType(A_CONSTANT_STRING);
return (IAnInterface)Activator.CreateInstance(type);
}
When the test is running, the type obtained from the Type.GetType(...)
method is null. 运行测试时,从Type.GetType(...)
方法获得的类型为null。 My questions are: 我的问题是:
null
is being returned because not all the types are loaded(?) when the tests are executed? 返回null
是因为执行测试时并非所有类型都已加载(?)? Thanks in advance 提前致谢
As @Krekkon already mentioned Type.GetType() method requires the following string: 正如@Krekkon已经提到的那样, Type.GetType()方法需要以下字符串:
The assembly-qualified name of the type to get. 要获取的类型的程序集限定名称。 See AssemblyQualifiedName. 请参阅AssemblyQualifiedName。 If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace. 如果类型在当前正在执行的程序集中或在Mscorlib.dll中,则只需提供其名称空间限定的类型名称即可。
For question #2: You will not be able to test whether the type has been returned because of the static call to Type.GetType() . 对于问题2:由于对Type.GetType()的静态调用,您将无法测试是否已返回类型。 If you can change the code you could introduce an interface that is responsible for type resolving and represents a facades of the static GetType method call: 如果可以更改代码,则可以引入一个接口,该接口负责类型解析并表示静态GetType方法调用的外观:
interface ITypeResolver
{
Type GetType(string typeName);
}
class SomeClass
{
private readonly ITypeResolver typeResolver = ...;
public IAnInterface Instantiator()
{
var type = this.typeResolver.GetType(A_CONSTANT_STRING);
return (IAnInterface)Activator.CreateInstance(type);
}
}
Using an interface you are able to mock the ITypeResolver
and also test the implementation of ITypeResolver
interface in Isolation. 使用接口,您可以模拟ITypeResolver
,也可以在Isolation中测试ITypeResolver
接口的实现。
var type = Type.GetType("namespace.qualified.TypeName");
通过添加对在A_CONSTANT_STRING
指定的类型所在的项目的引用来解决。
What assembly is your type defined in? 您的类型定义在哪个程序集中? Assuming your method is in the same assembly as the type you are looking for, try: 假设您的方法与要查找的类型在同一程序集中,请尝试:
var type = Assembly.GetExecutingAssembly().GetTypes()
.First(t => t.Name == A_CONSTANT_STRING);
return (IAnInterface)Activator.CreateInstance(type);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.