簡體   English   中英

動態創建接口成員

[英]Dynamically create members of interface

我有一個View,它實現了一個接口。

我正在嘗試對此進行單元測試,但它變得很無聊...

聲明是:

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();
    }

我是否有觀點可以動態地做到這一點?

將View傳遞給方法,該方法將驗證其中的內容並自動調用並構造一個構造函數?

我無法完全確定您要尋找的內容,但這可能會有所幫助嗎?:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM