我可以从内存中的实例生成代码以便以后重新创建它吗?

本文关键字:新创建 创建 内存 实例 代码 我可以 | 更新日期: 2023-09-27 18:36:02

>想象一下,我有一个设置了属性的实例(例如,它是从数据库加载的),

从内存中的这个实例中,我想获取一个代码,其中包含在当前值上设置的所有公共属性,以便我可以在我的单元测试中使用它来重新创建实例。

VS中有什么技巧或任何我可以使用的工具吗?

谢谢

我可以从内存中的实例生成代码以便以后重新创建它吗?

由于它是您希望保存的公共属性,请查看序列化。它允许您将对象流式传输到二进制格式或 XML,并在以后检索它。流可以是内存流或文件,具体取决于您希望保存多长时间。下面是该 MSDN 页中的代码,显示如何将对象保存到 XML 文件并在以后读回:

public class Book
{
    public String title;
}       
public static void WriteXML()       
{
    // First write something so that there is something to read ...
    var b = new Book { title = "Serialization Overview" };
    var writer = new System.Xml.Serialization.XmlSerializer(typeof(Book));
    var wfile = new System.IO.StreamWriter(@"c:'temp'SerializationOverview.xml");
    writer.Serialize(wfile, b);
    wfile.Close();
}
public void ReadXML()
    // Now we can read the serialized book ...
    System.Xml.Serialization.XmlSerializer reader = 
        new System.Xml.Serialization.XmlSerializer(typeof(Book));
    System.IO.StreamReader file = new System.IO.StreamReader(
        @"c:'temp'SerializationOverview.xml");
    Book overview =  (Book)reader.Deserialize(file);
    file.Close();
    Console.WriteLine(overview.title);    
}

也就是说,如果您想使用它在单元测试中重新创建对象,我不确定序列化是最佳选择。通常,您将创建一个单独的(可能在内存中)数据库,或者模拟数据库接口以返回硬编码对象。例如,假设您有以下生产代码:

public interface IDataAccess {
   User GetUserById(int userId);
}
public class SqlServerDataAccess : IDataAccess { 
   public User GetUserById(int userId) {
     // ... connect to database and retrieve user
   }
}

然后对于你的单元测试,你可以写一个实现

public class MockDataAccess : IDataAccess { 
   public User GetUserById(int userId) {
     return new User() { 
       Name = "pencilCake", ...
     }
   }
}

并将其用于单元测试。甚至还有像Moq和Rhino这样的框架,可以让你"即时"创建这样的接口,允许你为每个测试方法返回一个特定的硬编码对象。