在运行时期间获取对象值,以创建编写单元测试所需的Mock对象

use*_*158 6 c# unit-testing visual-studio

考虑下面需要测试的类,

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...  
    }
Run Code Online (Sandbox Code Playgroud)

问题Employee实际上可能是一个非常复杂的类型,其中包含属性,它们本身可以是更多类的对象.使用模拟值初始化Employee并生成可测试对象变得很困难.

在调试时,我可以设置断点并查看包含的Employee对象ToBeTested.有没有办法可以在运行时获取此对象中的所有值并在我的测试方法中使用它?

Car*_*ine 8

您可以使用Object Exporter.它是Visual Studio的扩展,它将从调试窗口中的任何对象生成C#初始化代码.您可以在单元测试初始化​​中使用此生成的代码.