I have a class similar to the following
class ObjectCaller
{
public void Process (String NameSpace) {
Type t = Type.GetType(NameSpace + ".Main");
if (t != null)
{
if (t.IsSubclassOf(typeof(Window)))
{
Object obj = Activator.CreateInstance(t);
}
else {
throw new NotAbstractedException();
}
}
else {
throw new MainNotFoundException();
}
}
}
A namespece is passed to the Render()
Method of the class and the passed namespace should have a class .Main
and also the class should be abstracted from Window
class. Which is working fine. But I am unable to do unit test so that if the class Main
exists but it is not an abstract class of Window
, it should throw an exception.
[TestMethod()]
[ExpectedException(typeof(NotAbstractedException))]
public void MainNotAbstractedTest() {
ObjectCaller oc = new ObjectCaller();
oc.Process("name.space.of.class");
}
I have tried using MOQ to MOCK System.Type
classes IsSubClassOf
method and with searching have found that its not possible to MOCK static classes. And also I don't want to change ObjectCaller
just for the purpose of UnitTesting, Is there any possible way to make the method Process throw the exception NotAbstractedException
without changing the class i am loading dynamically or no changing ObjectCaller
?
Just test it by passing it a namespace which contains a class called Main
which isn't derived from Window
.
Now you may find that tricky because if Type.GetType(string)
is passed a value which is a non-assembly-qualified name, it will only look in mscorlib
and the calling assembly - which in your case is the production code assembly. So your options are:
Type.GetType
, but add a unit test to ensure that you don't have any classes called Main
which aren't derived from Window
. At that point, you can get rid of the IsSubclass
testSee more on this question at Stackoverflow