C++ 单元测试的异常处理 [英] Exception handling for Unit Tests in c++

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

问题描述

我正在尝试在 Nunit 框架上测试 C++ 代码,但我不断收到以下异常

I'm trying to test a c++ code on an Nunit framework but I keep getting the following Exception

System.Runtime.InteropServices.SEHException : External Component has thrown an exception.

这应该是完全正常的(我假设)无论如何我想忽略它.(即使用 ExpectedException)这是我的 .h 文件

which is supposedly perfectly normal (I assume) anyway I wanna ignore it. (i.e. Use ExpectedException) This is my .h file

 [Test, Description("Tests if an Entity has been successfully Locked")]
 void test_LockOperation();

和 .cpp 文件

 void TestDmObstacles::test_LockOperation()
{
  lockVal = DbtoDmObstaclesAdapter::lock( CmnGuid::parseString( L"3B6DB8F8-4BA7-DD11-B6A7-001E8CDE165C" ) );
  //When lock is successful the lockVal is 0
  Assert::AreEqual(0, lockVal);
}

我想使用 ExpectedException 但我不知道如何在 C++ 中使用它.我也尝试了 try/catch 方法,但它不起作用(我只是将断言放在 catch 块中)

I wanna use ExpectedException but I don't know how to do it in c++. I tried the try/catch method as well but it didn't work (I just put the Assertion in the catch block)

PS:我不能使用其他框架,它必须是 Nunit

PS: I can't use another framework it has to be Nunit

编辑

这是我使用的 try/catch 方法

Here is the try/catch approach I used

    void TestDmObstacles::test_LockOperation()
{
    try
    {
        lockVal = DbtoDmObstaclesAdapter::lock( CmnGuid::parseString( L"3B6DB8F8-4BA7-DD11-B6A7-001E8CDE165C" ) );
    }
    catch (...)
    {
        //Assert::Fail();
        Assert::AreEqual(0, lockVal);

    }
}

推荐答案

异常是预期的,还是可以接受的?

如果它是预期,那么你的单元测试框架应该有某种 API 允许你声明预期的异常,如果它没有发生,则使测试失败em>.快速浏览文档会产生咒语:

If it is expected, then your unit test framework should have some kind of API that allows you to state the expected exception, and to fail the test if it does not occur. A quick trawl through the documentation yields the incantation:

[ExpectedException( "System.ArgumentException" )]

(将 System.ArgumentException 替换为您期望的异常.)

(replace System.ArgumentException with the exception you're expecting.)

如果异常只是可以接受,那么我会说您的代码或您的测试已损坏.单元测试是为了测试预期的事情是否发生.如果您的测试中的结果只有可能产生特定结果,那么您没有在测试之间测试单元的一致视图.因此,您并没有真正测试它.

If the exception is merely acceptable, then I would say that either your code or your test is broken. A unit test is to test that expected things happen. If there is a result in your test that only may yield a particular result, then you are not testing a consistent view of the unit from test to test. Hence, you're not really testing it.

例如,这可能表明您的代码正在泄漏一个它应该处理的意外异常.

It might indicate, for example, that your code is leaking an unexpected exception that it should be handling instead.

这篇关于C++ 单元测试的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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