目前,我已经编写了一个存储实体的存储库。 该实体是一个对象,并且继承自基类“实体”。
public class Entity
{
#region Constructors
public Entity() : this(DateTime.Now, DateTime.Now) { }
public Entity(DateTime creationDate, DateTime updateDate)
{
DateCreated = creationDate;
DateUpdated = updateDate;
}
#endregion
#region Properties
[Key]
[Required]
[Column(Order= 0)]
public int Id { get; private set; }
[Required]
[Column(Order = 998)]
public DateTime DateCreated { get; private set; }
[Required]
[Column(Order = 999)]
public DateTime DateUpdated { get; internal set; }
#endregion
}
现在我想对持有实现实体的对象的存储库进行单元测试(而不是集成测试)。
我创建了一个假存储库,它使用HashSet将对象存储在内存中。 现在,问题在于,当我将实体添加到我的存储库时,所有Id值都被指定为“0”,这是正常的。
在实体框架上,它们被分配了一个唯一的int值(从0开始),由于数据注释,这也是正常的。
现在我想知道在运行单元测试时我是如何模仿数据注释的相同行为的,因为现在,我可以在我的存储库中有多个相同'Key'值的记录,这当然不应该在任何情况下都是可能的。
感谢。
答案 0 :(得分:0)
您已经在使用构造函数链接传递DateTime
和creationDate
的默认updateDate
值 - 为什么不再添加一个?
public class Entity
{
#region Constructors
public Entity() : this(DateTime.Now, DateTime.Now, default(int)) { }
public Entity(DateTime creationDate, DateTime updateDate, int id)
{
DateCreated = creationDate;
DateUpdated = updateDate;
Id = id
}
#endregion
#region Properties
[Key]
[Required]
[Column(Order= 0)]
public int Id { get; private set; }
[Required]
[Column(Order = 998)]
public DateTime DateCreated { get; private set; }
[Required]
[Column(Order = 999)]
public DateTime DateUpdated { get; internal set; }
#endregion
}
然后,您可以根据需要为每个实体生成唯一ID。
答案 1 :(得分:0)
听起来你正试图测试错误的东西。你到底想要完成什么? KeyAttribute
是存储层的实现细节,您不想测试它 - 供应商的工作是确保它有效。
虚拟存储库是一种测试其他依赖于存储库接口的其他东西的方法。因此,您可能应该做的是创建一个测试用例,其中您的存储库设置为抛出适用于重复键场景的异常,然后在遇到该异常时验证被测系统是否做了正确的事情。
但是,您可能希望确保所有实体的Id属性都有KeyAttribute
。您可以将其作为单个单元测试来枚举您的实体类型,并使用反射来验证属性的存在。