简体   繁体   中英

How write a unit test for verifying compiling error?

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.

Thanks in advance!

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, eg 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.

You did not specify the language

  • Ruby, Python -- dynamic & strong typesystem. This means that the types deduced during runtime (dynamic), but implicit conversions between types are prohibited
  • Js, Perl -- dynamic & weak typesystem.
  • C++ -- static and strong typesystem.

Let's assume we are talking about C++. Moreover I can create more really example. Imagine that you implement static assert for your project which doesn't not use c++11 compiler

template <bool> struct my_static_assert; template <> struct my_static_assert<true> {};

If you want to check that such mechanism works ok. You should create unittest function which do the follow steps:

  1. Create some file to compiler

  2. Create external process of the compiler and pass test compile unit to it

  3. Wait for compiler process completion

  4. Retrive return code from the compiler process

  5. Your function check return code from 4.

I checked google-test guide but it seems that they doesn't support such concept https://github.com/google/googletest/blob/master/docs/advanced.md

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM