【发布时间】:2012-09-24 13:07:31
【问题描述】:
我们的目的是生成一个字符串输出,该输出需要遵守一组特定的语法规则。我创建了一个对象模型,以便通过 C# 的强类型强制执行该语法,以防止生成无效输出的可能性。
我可以创建积极的测试,即有效的 C# 生成有效的输出。我无法做的是运行否定测试,即确保尝试生成无效输出会在编译时引发错误。
显式示例:
namespace Abstract
{
public interface FooType { }
public interface FooString : FooType { }
}
public interface Integer : Abstract.FooType { }
public interface SingleLine : Abstract.FooString { }
public interface MultiLine : Abstract.FooString { }
public class Bar<T>
where T : Abstract.FooType
{
public Bar(string s) {
// do stuff with s and T, where T is SingleLine or MultiLine
}
public Bar(int i) {
// do stuff with i and T, where T is Integer
}
}
public static class Foo
{
public static Bar<T> Bar<T>(int i) where T : Integer {
return new Bar<T>(i);
}
public static Bar<SingleLine> Bar(string s) {
return new Bar<SingleLine>(s);
}
public static Bar<T> Bar<T>(string s) where T : Abstract.FooString {
return new Bar<T>(s);
}
}
所有这些都是为了我能做到:
Foo.Bar<SingleLine>("some string"); // ok
Foo.Bar("another string"); // ok
Foo.Bar<MultiLine>("more\nstrings"); // still ok
Foo.Bar<Integer>(24) // also ok
// How to test these lines for compilation failure?
Foo.Bar<Integer>("no good");
Foo.Bar<MultiLine>(-1);
以防万一,我正在使用 VS2012 Express for Desktop。
【问题讨论】:
-
您的意思是,测试特定用途是否被编译器拒绝?
-
也许您可以在您的问题中添加一个示例,说明这种不可编译的代码可能是什么?
-
如果您的代码无法编译,您将无法对其进行测试。所以编译器会测试你的代码是否有语法错误。而且您只对运行时部分进行单元测试。
-
@Damien_The_Unbeliever 添加示例
-
您的示例看起来像是针对 C# 编译器的单元测试,而不是针对您的代码的单元测试。您想通过此测试检测什么样的错误?
标签: c# unit-testing compilation strong-typing