'Grab object values during runtime for creating Mock objects required for writing Unit Test
Consider the below class which needs to be tested,
class ToBeTested
{
Employee _e;
public ToBeTested(Employee e)
{
_e = e;
}
void Process()
{
// Do something with _e
}
}
[TestClass]
class ToBeTestedTest
{
[TestMethod]
public void TestProcessMethod()
{
Employee e = // Initialise it with some test value..
ToBeTested tbt = new ToBeTested(e);
tbt.Process();
//Assert to Verify the test results...
}
The Problem is Employee
can really be a very complex type with properties in it which themselves can be objects of more classes. It becomes difficult to initialise Employee with Mock Values and generate a testable object.
While debugging I can set a breakpoint and see what Employee
object in ToBeTested
contains. Is there a way by which I can grab all the values from this object as is available during runtime and use it in my test method?
Solution 1:[1]
You can use Object Exporter. Its an extension for Visual studio which will generate C# initialization code from any object in your debugging windows. You can use this generated code in your unit test initialization.
Solution 2:[2]
The mentioned Visual Studio Extension (OmarElabd/ObjectExporter) was a good idea, but I needed to generate C# code from in-memory objects at runtime, during unit test execution. This is what evolved from the original problem: https://www.nuget.org/packages/ObjectDumper.NET/
ObjectDumper.Dump(obj, DumpStyle.CSharp); returns C# initializer code from a variable. Please let me know if you find issues, you might want to report them on github.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |