单元测试编译时错误 [英] Unit test compile-time error

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

问题描述

有没有方法来测试编译时错误,但没有实际生成错误?例如,如果我创建一个不可复制的类,我想测试一个事实,试图复制它会生成一个编译器错误,但我仍然想执行其他运行时测试。

Is there a way to test compile-time errors, but without actually generating the error? For example, if I create a class which is non-copyable, I'd like to test the fact that trying to copy it will generate a compiler error, but I'd still like to execute the other runtime tests.

struct Foo {
    int value_;
    Foo(int value) : value_(value) {}
  private:
    Foo(const Foo&);
    const Foo& operator=(const Foo&);
};

int main()
{
    Foo f(12);
    assert(f.value_ == 12);
    assert(IS_COMPILER_ERROR(Foo copy(f);));
} // Would like this to compile and run fine.

我想这不能简单地做,但有一个惯用的方式这个,或者我应该滚动我自己的解决方案(可能使用脚本编译单独的测试文件和测试结果?)

I guess this can't be done as simply as that, but is there an idiomatic way to do this, or should I roll my own solution (maybe using scripts compiling separate tests files and testing the results?)?

注意:我采取不可复制只是为了说明我的点,所以我不感兴趣关于使用boost :: noncopyable等的答案。

N.B.: I took non-copyable only to illustrate my point, so I'm not interested in answers about using boost::noncopyable and such.

推荐答案

。每个测试将是一个代码片段。这里是一个工作示例与VC测试2。 (我使用了2个批处理文件通过测试和失败测试)。我在这里使用GNU make。

You can do it using make. Each test will be a code snippet. Here's a working example with 2 tests for VC++. (I've used 2 batch files for pass test and fail test). I'm using GNU make here.

Makefile:


FAILTEST = .\failtest.bat
PASSTEST = .\passtest.bat

tests: must_fail_but_passes \
    must_pass_but_fails

must_fail_but_passes:
    @$(FAILTEST) $@.cpp

must_pass_but_fails:
    @$(PASSTEST) $@.cpp

must_pass_but_fails.cpp

must_pass_but_fails.cpp


struct Foo {
    int value_;
    Foo(void) : value_(0) {}
  private:
    Foo(const Foo&);
    const Foo& operator=(const Foo&);
};

int main()
{
Foo f(12);
return 0;
}

int main() { Foo f(12); return 0; }

must_fail_but_passes.cpp

must_fail_but_passes.cpp


struct Foo {
    int value_;
    Foo(int value) : value_(value) {}
  private:
    Foo(const Foo&);
    const Foo& operator=(const Foo&);
};

int main()
{
Foo f(12);
return 0;
}

int main() { Foo f(12); return 0; }

passtest.bat

passtest.bat


@echo off
cl /nologo %1 >NUL
if %errorlevel% == 0 goto pass
@echo %1 FAILED
:pass

failtest.bat

failtest.bat


@echo off
cl /nologo %1 >NUL
if not %errorlevel% == 0 goto pass
@echo %1 FAILED
:pass

请注意,cl.exe(即Visual Studio编译器)

Note that cl.exe (i.e. Visual Studio compiler) need to be in your path for this to "just work"

有乐趣!

PS我怀疑这会让我着名,虽然: - )

P.S. I doubt that this would make me famous though :-)

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

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