简体   繁体   中英

Is it possible to check if shared pointer returns a nullptr in native unit test?

Using Visual Studio 2012 native unit test, the code can't be compiled when using shared pointer.

My code:

#include "stdafx.h"
#include "CppUnitTest.h"
#include "ParameterTest.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace MyParameter;

namespace MyParameterTests
{       
    TEST_CLASS(MyParameterTests)
    {
    public:

        TEST_METHOD(CheckParametersWithPathReturnsNotNull)
        {
            //Arrange
            Parameter parameter = Parameter();

            //Act
            std::shared_ptr<std::string> actual = parameter.CheckParameters("C:\\Parameter.db");

            //Assert
            Assert::IsNotNull(actual, L"Should not return null", LINE_INFO());

        }

    };
}

Compiler eror:

2>------ Rebuild All started: Project: MyParameterTests, Configuration: Debug Win32 ------ 2> stdafx.cpp 2> ParameterTestTests.cpp 2>c:\\users\\\\documents\\visual studio 2012\\projects\\myparametertests\\parametertests.cpp(26): error C2784: 'void Microsoft::VisualStudio::CppUnitTestFramework::Assert::IsNotNull(const T *,const wchar_t *,const Microsoft::VisualStudio::CppUnitTestFramework::__LineInfo *)' : could not deduce template argument for 'const T *' from 'std::shared_ptr<_Ty>' 2> with 2> [ 2> _Ty=std::string 2> ] 2> c:\\program files (x86)\\microsoft visual studio 11.0\\vc\\unittest\\include\\cppunittestassert.h(259) : see declaration of 'Microsoft::VisualStudio::CppUnitTestFramework::Assert::IsNotNull'

You should replace

Assert::IsNotNull(actual, L"Should not return null", LINE_INFO()); 

with

Assert::IsNotNull(actual.get(), L"Should not return null", LINE_INFO());

Indeed, the assertion wants a pointer to check if it's null, but a smart-pointer isn't a pointer strictly speaking (it's an object that manages a pointer).

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