我如何对移动操作进行单元测试(默认)?

问题描述 投票:0回答:1

当我尝试为仅移动类编写单元测试时遇到了这个问题。 [我不知道如何编写测试来检查移动操作是否确实移动了类的数据成员。在这里,我提供了一个与我正在研究的并行的类的简化示例。实际上,该类支持更多的操作和(std::multimap)数据成员,在这里不相关。

#include <vector>

class MyClass {
 public:
  inline MyClass() = default;

  MyClass(const MyClass& other) = delete;
  MyClass(MyClass&& other) = default;

  MyClass& operator=(const MyClass& other) = delete;
  MyClass& operator=(MyClass&& other) = default;

  ~MyClass() = default;

  inline void set(const std::vector<MyStruct>& data) {data_ = data;}
  inline const std::vector<MyStruct>& get() {return data_;}
 private:
  std::vector<MyStruct> data_;
};

[MyStruct]仅包含原始数据类型(intfloatdouble),并且某些std::string类型作为(public)数据成员。为了完整起见,我在末尾添加了MyStruct的定义。

我不确定该如何开始,也无法通过在线搜索找到任何东西。理想情况下,googletest或googlemock解决方案将是很好的选择,但是仅是通用方法或在其他测试框架中如何完成它,可能会帮助我理解并在首选的框架中实现。

#include <string>

struct MyStruct {
  int foo;
  float bar;
  double baz;
  std::string fips;
};
c++ unit-testing googletest move-semantics googlemock
1个回答
0
投票

这里是一种使用Marker成员变量跟踪对象状态的方法。请记住,std::move并不意味着将对象[[will从中移出,而只是使对象eligible从中被移出。

一旦将对象从其移出,其处于“有效但未指定的状态”,适合于销毁或重新分配给该对象。 (一些标准C ++库类型在移出后的状态方面具有更强的保证,例如std::vectorstd::unique_ptr。)

#include <iostream> #include <string> #include <vector> #ifndef TESTING #define TESTING 1 #endif namespace { struct Marker final { char const* state; ~Marker() { state = "destructed"; } Marker() : state{"constructed"} {} Marker(Marker const&) noexcept : state{"copy constructed"} {} Marker(Marker&& other) noexcept : state{"move constructed"} { other.state = "move constructed husk"; } Marker& operator=(Marker const&) noexcept { state = "assigned"; return *this; } Marker& operator=(Marker&& other) noexcept { state = "move assigned"; other.state = "move assigned husk"; return *this; } void print(std::ostream&) const; }; void Marker::print(std::ostream& out) const { out << state; } std::ostream& operator<<(std::ostream& out, Marker const& marker) { marker.print(out); return out; } class BigFancyClass { std::vector<std::string> v; public: BigFancyClass() {} BigFancyClass(BigFancyClass const&) = default; BigFancyClass(BigFancyClass&&) = default; #if TESTING Marker mark; #endif }; void test() { BigFancyClass bfc; std::cout << "bfc: " << bfc.mark << "\n"; BigFancyClass bfc2 = std::move(bfc); std::cout << "bfc: " << bfc.mark << "\n"; std::cout << "bfc2: " << bfc2.mark << "\n"; } } // anon int main() { test(); }

© www.soinside.com 2019 - 2024. All rights reserved.