Sadly, references to this exception are usually of an exotic nature and can happen when you e.g. enumerate Types via Assembly.GetTypes()
- case in point, it is
Another approach if you wish to test how your code handles the exception is to use mocking in your testing. With mocking you can mock out the assembly loading sub-system and concentrate on testing how you handle the resulting exception - much more straight-forward.
Using mocking you would use an IAssemblyService
instead of calling GetTypes
on Assembly
directly. In your mock you can throw the required exception. It is more usual to use a mocking framework such as FakeItEasy, but the following uses a hand-rolled mock for demonstration.
In your test you would substitute your real assembly service with MockAssemblyService
.
internal class MyTypeThatLoadsStuff
{
public MyTypeThatLoadsStuff(IAssemblyService assemblyService)
{
//Do stuff with assemblyService
}
}
internal interface IAssemblyService
{
IEnumerable GetTypes();
}
internal class AssemblyService : IAssemblyService
{
private readonly Assembly _assembly;
public AssemblyService(Assembly assembly)
{
_assembly = assembly;
}
public IEnumerable GetTypes()
{
return _assembly.GetTypes();
}
}
internal class MockAssemblyService : IAssemblyService
{
public IEnumerable GetTypes()
{
throw new ReflectionTypeLoadException();
}
}
And with a mocking framework such as FakeItEasy:
[Test]
public void Test()
{
IAssemblyService service = A.Fake();
ReflectionTypeLoadException ex = new ReflectionTypeLoadException(
new[] { typeof(SprocketTests) }, new[] { new Exception() });
A.CallTo(() => service.GetTypes()).Throws(ex);
MyTypeThatLoadsStuff loader = new MyTypeThatLoadsStuff(service);
//test...
}