问题
I have a View, that implements an interface.
I'm trying to unit test this, but it gets boring...
The declaration is:
public interface IView : IBaseView
{
TextBox ClientId { get; set; }
TextBox ClientName { get; set; }
Button SaveClient { get; set; }
Button NextClient { get; set; }
Button PreviousClient { get; set; }
Button DiscardChanges {get;set;}
bool ReadOnly { get; set; }
ListBox MyLittleList { get; set; }
}
[Test]
public void FirstSteps()
{
var sessionFactory = Substitute.For<ISessionFactory>();
var session = Substitute.For<ISession>();
var statelessSession = Substitute.For<IStatelessSession>();
sessionFactory.OpenSession().Returns(session);
sessionFactory.OpenStatelessSession().Returns(statelessSession);
var view = Substitute.For<IView>();
view.ClientId = new System.Windows.Forms.TextBox();
view.ClientName = new System.Windows.Forms.TextBox();
view.DiscardChanges = new System.Windows.Forms.Button();
view.MyLittleList = new System.Windows.Forms.ListBox();
view.NextClient = new System.Windows.Forms.Button();
view.PreviousClient = new System.Windows.Forms.Button();
view.ReadOnly = false;
view.SaveClient = new System.Windows.Forms.Button();
}
Is there a view for me to dynamically do that?
Pass the View to a method, that will verify what is there and automatically call a constructor on and set it?
回答1:
Im not fully sure what you are looking for but maybe this might help a bit?:
public static void SetData<T>(T obj)
{
foreach (var property in typeof(T).GetProperties())
if (property.CanWrite && property.GetIndexParameters().Length == 0)
{
object val = null;
//// Optionally some custom logic if you like:
//if (property.PropertyType == typeof(string))
// val = "Jan-Peter Vos";
//else
val = Activator.CreateInstance(property.PropertyType);
property.SetValue(obj, val, null);
}
}
[Test]
public void FirstSteps()
{
// .. Your code ..
SetData(view);
}
来源:https://stackoverflow.com/questions/13752373/dynamically-create-members-of-interface