為Asp.net控件寫單元測試(ViewState)[2]
為Asp.net控件寫單元測試(ViewState)[2] 單元測試代碼 // Interface to expose protected methods from // the Control class to our unit test internal interface IControl { void LoadViewState(object savedState); object SaveViewState(); void TrackV
為Asp.net控件寫單元測試(ViewState)[2] 單元測試代碼
// Interface to expose protected methods from // the Control class to our unit test internal interface IControl { void LoadViewState(object savedState); object SaveViewState(); void TrackViewState(); }
|
然后讓我們的控件去實現它:
#region IControl Members void IControl.LoadViewState(object savedState) { LoadViewState(savedState); } object IControl.SaveViewState() { return SaveViewState(); } void IControl.TrackViewState() { TrackViewState(); } #endregion
|
現在就可以測試ViewState了:
[TestMethod] public void TextSavedInViewState() { // Create the control, start tracking viewstate, // then set a new Text value const string firstValue = "Some Text"; const string secondValue = "ViewState Text"; NewLabel label = new NewLabel(); label.Text = firstValue; ((IControl)label).TrackViewState(); label.Text = secondValue; // Save the control's state object viewState = ((IControl)label).SaveViewState(); // Create a new control instance and load the state // back into it, overriding any existing values NewLabel newLabel = new NewLabel(); label.Text = firstValue; ((IControl)newLabel).LoadViewState(viewState); Assert.AreEqual(secondValue, newLabel.Text, "Value restored from viewstate does not match the original value we set"); }
|
這里注意一點,我們的接口是internal的,為了讓測試用例可以訪問它,需要添加 軟件測試
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("MyControlLibrary.Test")]
|
原文轉自:http://www.kjueaiud.com