I tried to find an example of this but without success so that's is why I asked this question.
Lets start with some code. Here's my code:
class Dummy
{
public void DoDummyThings1()
{
Console.WriteLine("Sorry, I'm dummy 1...");
}
public void DoDummyThings2()
{
Console.WriteLine("Sorry, I'm dummy 2...");
}
public void DoDummyThings3()
{
Console.WriteLine("Sorry, I'm dummy 3...");
}
}
And my test code:
[TestClass]
public class UnitTest
{
private Dummy dum = new Dummy();
[TestInitialize()]
public void SetUp()
{
MethodInfo mi = typeof (UnitTest).GetMethod("TestDummy");
MethodBody mb = mi.GetMethodBody();
}
[TestMethod]
public void TestDummy()
{
this.dum.DoDummyThings1();
this.dum.DoDummyThings2();
this.dum.DoDummyThings3();
}
}
Here's what I'm trying to do. I want to, before execution of each test method, look to the test method and check if methods DoDummyThings1,DoDummyThings2 and DoDummyThings3 of Dummy class will be called or not.
The purpose of this is, depending of which DoDummyThingsX methods are called, I want to inject different implementation somewhere deep inside the code to modify during runtime the behavior of some class (swap the inject implementation of an interface for another one).
Can somebody explain me how to do this correctly (with lastest version of Cecil or something else for C#)? Is there a way to do this without using the .dll files? (Currently, this is the only way I figured out how to do this but, using strings as "MyDllName.dll" and "MyNamespace.MyClassName" hard coded are not possible for me)
Other stackoverflow threads I'm already aware of:
- Look if a method is called inside a method using reflection
- How to determine which methods are called in a method?
- Can I use reflection to inspect the code in a method?
Can anyone help me with a complete (but simple) example (if it's possible)? Thank you!