如何编写单元测试来验证编译错误? [英] How write a unit test for verifying compiling error?

查看:21
本文介绍了如何编写单元测试来验证编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个测试来验证编译错误.这是关于为 String 类型属性分配一个数字.但由于这是一个编译错误,单元测试代码甚至不会首先被编译.那么有人对如何做到这一点有任何建议吗?

I'm trying to write a test to verify a compiling error. It's about assigning a number to a String type property. But since it's a compiling error, the unit test code won't even be compiled at the first place. So anyone have any suggestion on how to do this?

我在想也许我可以在运行时分配数字并检查是否抛出了某些异常?但我不确定如何做到这一点.

I'm thinking maybe I can assign the number in runtime and check to see if certain exception got thrown? But I'm not sure how exactly to do that.

提前致谢!

推荐答案

如果我理解正确,您有一些可能无法编译的代码,并且您想编写单元测试,如果代码确实没有编译通过,则该单元测试会失败编译.如果是这种情况,那么您不应该编写任何单元测试.你应该明白你应该只为你的代码编写单元测试,而不是其他人编写的代码.

If I understand you correctly, you have some piece of code that may not compile and you want to write the unit test that fails if the code really doesn't compile. If that is the case, then you should not write any unit tests. You should understand that you should write unit tests only for your code, not the code that somebody else wrote.

你没有指定编程语言,所以我会做一些伪代码.假设您正在编写一个将两个数字相加的函数:

You didn't specify the programming language, so I will do some pseudo-code. Say you are writing a function to add two numbers:

function add(a, b) {
   return a + b;
}

很简单.您应该对此进行单元测试,例如通过进行如下测试:

Very simple. You should unit test this, e.g. by making tests like the below:

function testAdd() {
   assertEquals(4, add(2, 2));
   assertEquals(46, add(12, 34));
}

但是,您应该不要编写一个测试来测试 + 运算符是否正常工作.这是编写实现 + 运算符真正工作方式的库的人的工作.

However, you should not write a test that tests whether + operator is working fine. This is the job of whoever wrote the library that implements how + operator really works.

因此,如果是这种情况,请不要编写任何单元测试.编译代码是编译器的工作.编译器应该以正确的方式报告存在编译错误.你不应该测试编译器是否正确地完成了它的工作——测试是编写编译器的人的工作.

So, if that's the case, don't write any unit tests. Compiling your code is job of your compiler. The compiler should report that there is a compilation error in a proper way. You should not test whether compiler does its job correctly - testing that is the job of the people who are writing the compiler.

这篇关于如何编写单元测试来验证编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆