[英]Is it feasible to use Func<T, TResult> or Action<T> to achieve this?
為了重新組織單元測試,我目前正在尋找實現這一目標的不同可能性:
[TestClass]
public class CustomerTests : SuperTestBaseClass {
public CustomerTests() : base() { }
[TestMethod]
public void NameThrowsWhenNull() {
Throws<ArgumentNullException>(customer.Name = null);
}
}
public abstract class SuperTestBaseClass {
protected SuperTestBaseClass() { }
public void Throws<TException>(Func<T, TResult> propertyOrMethod) {
// arrange
Type expected = typeof(TException);
Exception actual = null;
// act
try { propertyOrMethod(); } catch (Exception ex) { actual = ex; }
// assert
Assert.IsInstanceOfType(actual, expected);
}
}
在哪里可以在try/catch
執行propertyOrMethod
,而無需編寫類似以下內容的代碼:
try { propertyOrMethod.Name = null } catch...
因為目標是使這種方法成為最通用的方法,以促進代碼重用。
可行嗎 如果是,那怎么辦?
在您的方法上使用[ExpectedException(typeof(ArgumentNullException)]
,您將不需要任何自定義內容。
[TestClass]
public class CustomerTests : SuperTestBaseClass {
public CustomerTests() : base() { }
[TestMethod]
[ExpectedException(typeof(ArgumentNullException)]
public void NameThrowsWhenNull() {
customer.Name = null;
}
}
我會做:
public TException Throws<TException>(Action act) where TException : Exception
{
// act
try { act(); } catch (TException ex) { return ex; }
// assert
Assert.Fail("Expected exception");
return default(TException); //never reached
}
那你可以做
Throws<ArgumentNullException>(() => { customer.Name = null; });
請注意,NUnit內置了此方法( Assert.Throws/Catch
),因此,如果使用它,則不需要此方法。
如果使用NUnit,則可以執行以下操作:
Assert.That(() => { ... }, Throws.InstanceOf<ArgumentException>()));
如果需要,可以將lambda表達式替換為委托實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.