Mock static method Activator.CreateInstance to return a mock of another class
Posted
by
Jeep87c
on Stack Overflow
See other posts from Stack Overflow
or by Jeep87c
Published on 2013-06-28T21:49:00Z
Indexed on
2013/06/28
22:21 UTC
Read the original article
Hit count: 430
I have this factory class and I want to test it correctly. Let's say I have an abstract class which have many child (inheritance).
As you can see in my Factory class the method BuildChild, I want to be able to create an instance of a child class at Runtime. I must be able to create this instance during Runtime because the type won't be know before runtime. And, I can NOT use Unity for this project (if so, I would not ask how to achieve this).
Here's my Factory class that I want to test:
public class Factory
{
public AnAbstractClass BuildChild(Type childType, object parameter)
{
AnAbstractClass child = (AnAbstractClass) Activator.CreateInstance(childType);
child.Initialize(parameter);
return child;
}
}
To test this, I want to find a way to Mock Activator.CreateInstance to return my own mocked object of a child class. How can I achieve this? Or maybe if you have a better way to do this without using Activator.CreateInstance (and Unity), I'm opened to it if it's easier to test and mock!
I'm currently using Moq to create my mocks but since Activator.CreateInstance is a static method from a static class, I can't figure out how to do this (I already know that Moq can only create mock instances of objects).
I took a look at Fakes from Microsoft but without success (I had some difficulties to understand how it works and to find some well explained examples).
Please help me!
EDIT:
I need to mock Activator.CreateInstance because I want to force this method to return another mocked object. The correct thing I want is only to stub this method (not to mock it).
So when I test BuildChild like this:
[TestMethod]
public void TestBuildChild()
{
var mockChildClass = new Mock(AChildClass);
// TODO: Stub/Mock Activator.CreateInstance to return mockChildClass when called with "type" and "parameter" as follow.
var type = typeof(AChildClass);
var parameter = "A parameter";
var child = this._factory.BuildChild(type, parameters);
}
Activator.CreateInstance called with type and parameter will return my mocked object instead of creating a new instance of the real child class (not yet implemented).
© Stack Overflow or respective owner