如果您需要从另一个项目中测试非公共属性,Microsoft单元测试向导会创建Accessor对象。在我的单元测试中,我创建了辅助函数,这样我就不会在每个单元测试方法中重复相同的代码。目前我有两个几乎完全相同的测试,除了一个采用标准公共对象,另一个采用Accessor版本。由于Accessor基于公共对象,所以我应该能够拥有一个功能。我曾假设我可以使用泛型来完成一个简单的演员。但在posting the question之后,我发现还有很多工作要做,包括必须更新底层对象。我的问题是另一种方法来减少这些冗余方法只有一个功能使用铸造(或其他)的方法?最佳方式更新使用共享函数的两个常用函数
下面是现有的两个功能:
// Common function to create a new test record with standard Account object
internal static void CreateAccount(out Account account, bool saveToDatabase)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
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 void CreateAccount(out Account_Accessor account, bool saveToDatabase)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
account = new Account_Accessor(created, createdBy);
account.Notes = Utilities.RandomString(1000);
if (saveToDatabase)
account.Create();
}
我有这些单元测试的两打和真实对象有10个属性的平均值,我在这里简单的例子。
下面是单元测试API创建的访问器代码(再次,我已经降低下来,以简化的例子):
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("[email protected]")]
public Account_Accessor(DateTime created, string createdBy);
[Shadowing("_notes")]
public string _notes { get; set; }
public static Account_Accessor AttachShadow(object value);
[Shadowing("[email protected]")]
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("[email protected]")]
public void add_PropertyChanged(PropertyChangedEventHandler value);
public static ProjectBase_Accessor<T> AttachShadow(object value);
[Shadowing("[email protected]")]
public virtual void Create();
}
}
'Account'和'Account_Accessor'之间的区别是什么? –
无视我的答案。因为这显然与你的其他问题的答案完全相同。 http://stackoverflow.com/a/12998986/2009。换句话说,我认为泛型实际上是你用最少的工作量来完成的方法。 – hometoast
我在我的问题中添加了代码访问器代码,正如@dthorpe指出的那样,Accessor继承自BaseShadow(在它通过我们的Base类之后)。 – Josh