class里面构造函数显式的设置为delete状态,
也有构造函数显式的设置为 noexcept
则UT如何测试到呢?
#ifndef YOUR_OWN_FILEDESCRIPTOR_HPP_
#define YOUR_OWN_FILEDESCRIPTOR_HPP_
#include "System.hpp"
namespace your_own_engine
{
class System;
class FileDescriptor
{
public:
explicit FileDescriptor(int fd) noexcept;
FileDescriptor(System& system, int fd) noexcept;
FileDescriptor(FileDescriptor&& fd) noexcept;
FileDescriptor(const FileDescriptor&) = delete;
FileDescriptor& operator=(const FileDescriptor&) = delete;
~FileDescriptor();
operator int() const noexcept
{
return fd_;
}
void close();
bool isClosed() const noexcept
{
return (fd_ < 0);
}
private:
System& system_;
int fd_;
};
} // namespace your_own_engine
#endif // YOUR_OWN_FILEDESCRIPTOR_HPP_
#include "FileDescriptor.hpp"
#include <fcntl.h>
#include <unistd.h>
namespace your_own_engine
{
FileDescriptor::FileDescriptor(int fd) noexcept : FileDescriptor(System::getSystem(), fd)
{
}
FileDescriptor::FileDescriptor(System& system, int fd) noexcept : system_(system), fd_(fd)
{
}
FileDescriptor::~FileDescriptor()
{
close();
}
void FileDescriptor::close()
{
if (fd_ < 0)
return;
system_.close(fd_);
fd_ = -1;
}
} // namespace your_own_engine
UT用例,注意
std::is_copy_assignable<FileDescriptor>::value
std::is_copy_constructible<FileDescriptor>::value
std::is_default_constructible<FileDescriptor>::value
#include "private/FileDescriptor.hpp"
#include <gtest/gtest.h>
#include <vector>
#include <memory>
#include <sys/eventfd.h>
#include <tst/SystemMock.hpp>
using namespace testing;
using namespace trsconnectorapi;
using namespace trsconnectorapi::tst;
namespace
{
class FileDescriptorTest : public Test
{
public:
NaggyMock<SystemMock> systemMock_;
};
} // namespace
TEST_F(FileDescriptorTest, IsNotCopyable)
{
EXPECT_FALSE(std::is_copy_assignable<FileDescriptor>::value);
EXPECT_FALSE(std::is_copy_constructible<FileDescriptor>::value);
}
TEST_F(FileDescriptorTest, IsNotDefaultConstructible)
{
EXPECT_FALSE(std::is_default_constructible<FileDescriptor>::value);
}
TEST_F(FileDescriptorTest, IsNoThrowConstructible)
{
EXPECT_TRUE((std::is_nothrow_constructible<FileDescriptor, int>::value));
EXPECT_TRUE((std::is_nothrow_constructible<FileDescriptor, System&, int>::value));
}
TEST_F(FileDescriptorTest, IsNoThrowMovable)
{
EXPECT_TRUE(std::is_nothrow_move_constructible<FileDescriptor>::value);
}
TEST_F(FileDescriptorTest, IsConvertibleToInt)
{
EXPECT_CALL(systemMock_, close(1)).Times(1);
EXPECT_EQ(-1, FileDescriptor(-1));
EXPECT_EQ(1, FileDescriptor(systemMock_, 1));
}
TEST_F(FileDescriptorTest, WhenDestructedFileDescriptorIsClosed)
{
EXPECT_CALL(systemMock_, close(1)).Times(1);
FileDescriptor(systemMock_, 1);
}
TEST_F(FileDescriptorTest, InvalidFileDescriptorIsNotClosed)
{
EXPECT_CALL(systemMock_, close(_)).Times(0);
FileDescriptor(systemMock_, -1);
}
TEST_F(FileDescriptorTest, CanCloseExplicitly)
{
FileDescriptor fd(systemMock_, 123);
EXPECT_FALSE(fd.isClosed());
EXPECT_CALL(systemMock_, close(123)).Times(1);
fd.close();
EXPECT_TRUE(fd.isClosed());
}