如果需要测试其他项目的非公共属性,Microsoft单元测试向导会创建Accessor对象。在我的单元测试中,我创建了辅助函数,这样我就不会在每个单元测试方法中重复相同的代码。目前我有两个几乎相同的测试,除了一个采用标准公共对象,另一个采用Accessor版本。由于Accessor基于标准版本,因此我应该能够拥有一个功能。
我曾经假设我可以使用Generics来完成一个简单的演员。但在posting the question之后我发现它还有很多工作要做,包括必须更新底层对象。当我询问是否存在任何其他方法时,这已得到证实。有人建议Dynamic objects might work。我不熟悉动态对象,是否有人发布了一个允许我拥有一个共享函数并在运行时确定对象的示例?
以下是现有的两个功能:
// Common function to create a new test record with standard Account object
internal static Account CreateAccount(bool saveToDatabase)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
Account account = new Account(created, createdBy);
account.Notes = Utilities.RandomString(1000);
if (saveToDatabase)
account.Create();
}
// Common function to create a new test record with Account_Accessor
internal static Account_Accessor CreateAccount(bool saveToDatabase)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
Account_Accessor account = new Account_Accessor(created, createdBy);
account.Notes = Utilities.RandomString(1000);
if (saveToDatabase)
account.Create();
}
我有二十几个单元测试,真实对象平均有10个属性,我在这里简化了示例。
以下是单元测试API创建的Accessor代码(同样,我已将其缩减以简化示例):
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.ObjectModel;
using System.Data;
namespace NameHere.Bll
{
[Shadowing("NameHere.Bll.Account")]
public class Account_Accessor : ProjectBase_Accessor<Account>
{
protected static PrivateType m_privateType;
public Account_Accessor(PrivateObject value);
[Shadowing(".ctor@2")]
public Account_Accessor(DateTime created, string createdBy);
[Shadowing("_notes")]
public string _notes { get; set; }
public static Account_Accessor AttachShadow(object value);
[Shadowing("Create@0")]
public override void Create();
}
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ComponentModel;
using System.Linq.Expressions;
namespace NameHere.Bll
{
[Shadowing("NameHere.Bll.ProjectBase`1")]
public class ProjectBase_Accessor<T> : BaseShadow, INotifyPropertyChanged
{
protected static PrivateType m_privateType;
public ProjectBase_Accessor(PrivateObject value);
[Shadowing("Created")]
public DateTime Created { get; set; }
public static PrivateType ShadowedType { get; }
[Shadowing("add_PropertyChanged@1")]
public void add_PropertyChanged(PropertyChangedEventHandler value);
public static ProjectBase_Accessor<T> AttachShadow(object value);
[Shadowing("Create@0")]
public virtual void Create();
}
}
答案 0 :(得分:0)
这是我第一次尝试使用动态对象的共享函数。它返回一个Account或Account_Accessor,具体取决于布尔值useAccessor param:
internal static dynamic CreateAccount(bool saveToDatabase, bool useAccessor)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
dynamic account;
if (useAccessor)
account = new Account_Accessor(created, createdBy);
else
account = new Account(created, createdBy);
account.Notes = Utilities.RandomString(1000);
if (saveToDatabase)
account.Create();
}
对此方法有何建议或意见?