I am working on mocking some external dependencies and am having trouble with one 3rd party class that takes in it's constructor an instance of another 3rd party class. Hopefully the SO community can give me some direction.
I want to create a mock instance of SomeRelatedLibraryClass
that takes in it's constructor a mock instance of SomeLibraryClass
. How can I mock SomeRelatedLibraryClass
this way?
The repo code...
Here is a Main method that I am using in my test console application.
public static void Main()
{
try
{
SomeLibraryClass slc = new SomeLibraryClass("direct to 3rd party");
slc.WriteMessage("3rd party message");
Console.WriteLine();
MyClass mc = new MyClass("through myclass");
mc.WriteMessage("myclass message");
Console.WriteLine();
Mock<MyClass> mockMc = new Mock<MyClass>("mock myclass");
mockMc.Setup(i => i.WriteMessage(It.IsAny<string>()))
.Callback((string message) => Console.WriteLine(string.Concat("Mock SomeLibraryClass WriteMessage: ", message)));
mockMc.Object.WriteMessage("mock message");
Console.WriteLine();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
Here is a class that I have used to wrap one third party class and allow it to be Moq'd:
public class MyClass
{
private SomeLibraryClass _SLC;
public MyClass(string constructMsg)
{
_SLC = new SomeLibraryClass(constructMsg);
}
public virtual void WriteMessage(string message)
{
_SLC.WriteMessage(message);
}
}
Here are two examples of 3rd party classes I am working with (YOU CAN NOT EDIT THESE):
public class SomeLibraryClass
{
public SomeLibraryClass(string constructMsg)
{
Console.WriteLine(string.Concat("SomeLibraryClass Constructor: ", constructMsg));
}
public void WriteMessage(string message)
{
Console.WriteLine(string.Concat("SomeLibraryClass WriteMessage: ", message));
}
}
public class SomeRelatedLibraryClass
{
public SomeRelatedLibraryClass(SomeLibraryClass slc)
{
//do nothing
}
public void WriteMessage(string message)
{
Console.WriteLine(string.Concat("SomeRelatedLibraryClass WriteMessage: ", message));
}
}