2015-11-20 56 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

为什么哦为什么我不服用蓝色药丸? –