2015-11-20 103 views
0

我正在實現類似於NUnit's Assert的自定義Assert類。使用靜態方法的泛型的解決方法

我們有Sonar打開StyleCop規則,它抱怨說我應該總是使用泛型而不是object。如果我將我的類更改爲通用類,那麼我陷入泛型類不能有靜態方法的規則。

例如,考慮這個代碼(我目前的方法非常簡化的版本):

public class Assert 
{ 
    public static void PropertyHasValue(object obj, string propertyName, object expectedValue) 
    { 
     var value = obj.GetType().GetProperty(propertyName).GetValue(obj, null); 
     Assert.AreEqual(expectedValue, value); 
    } 
} 

有實例方法在斷言類將沒有任何意義,我opnion。一個通用的方法會強迫我做這樣的事情(未經測試)想要使用的TestCase時:

[TestCase("someProperty", 10)] 
[TestCase("anotherProperty", "someString")] 
public void TestMethod(string propertyName, object expectedValue) 
{ 
    Assert.PropertyHasValue<object>(myObj, propertyName, expectedValue); 
} 

我怎麼能最好的重構這個類同時遵守這些規則?

+0

你能舉例說明嗎?你有沒有考慮過擴展方法? –

+6

類不一定是通用的。使該方法通用。 – MarcinJuraszek

回答

4

我會問一個不同的問題:爲什麼你會需要像這樣的方法?

是不是Assert.PropertyHasValue(foo, "bar", true)Assert.AreEqual(foo.bar, true)相同?

它是:

    清潔
  • 沒有機會使屬性名稱拼寫錯誤
  • 你編譯時安全

如果你真的需要做到這一點,你會可能要使用Func<U, T>而不是string來指定您的屬性:

public static class Assert 
{ 
    public static void PropertyHasValue<T,U>(T obj, Func<T, U> propertyGetter, U expectedValue) 
    { 
     var value = propertyGetter(obj); 
     Assert.AreEqual(expectedValue, value); 
    } 
} 
+0

爲什麼哦爲什麼我不服用藍色藥丸? –