简体   繁体   English

我可以使用EXPECT_CALL来验证模拟对象的构造函数是否多次调用成员函数吗?

[英]Can I use EXPECT_CALL to verify if the mock object's constructor calls a member function certain times?

I have a class whose constructor calls a member function, which in turn calls other member functions. 我有一个其构造函数调用成员函数的类,该成员函数又调用其他成员函数。 I want to use GMock to create a mock class and verify that, when a mock class object is constructed, those member functions were called exactly once each during the construction. 我想使用GMock创建一个模拟类,并验证在构造模拟类对象时,这些成员函数在构造过程中分别被调用一次。 But I am observing the following dilemma: 但是我遇到了以下难题:

  • On one hand, according to GMock's Dummy doc , "Google Mock requires expectations to be set before the mock functions are called, otherwise the behavior is undefined." 一方面,根据GMock的Dummy文档 ,“ Google Mock需要在调用模拟函数之前设置期望值,否则行为是不确定的。” So you have to call EXPECT_CALL() before the object's constructor is executed. 因此,必须在执行对象的构造函数之前调用EXPECT_CALL()。

  • On the other hand, EXPECT_CALL() needs an object as its first argument, so we have to construct the object before we can set the expectation. 另一方面,EXPECT_CALL()需要一个对象作为其第一个参数,因此我们必须先构造该对象,然后才能设置期望值。

Is the above observation correct and, if so, is there still a way to achieve what I am hoping to do? 上述观察是否正确?如果是,是否还有办法实现我希望做的事情?

It sounds like you're going to end up testing the Mock of your class, but that's not very helpful. 听起来您将要测试班级的Mock,但这不是很有帮助。 The mocked constructor will not make calls to the member functions by default, so your EXPECT_CALL() 's would need to be paired with forcing the Mock to make those function calls. 默认情况下, EXPECT_CALL()构造函数不会调用成员函数,因此需要将您的EXPECT_CALL()与强制Mock进行配对。 Not a useful situation to getting your code's behaviour into an automated test harness. 将代码的行为纳入自动测试工具中不是有用的情况。

Instead of trying to test the implementation details of your class, can you create the object and use EXPECT calls on the public interface to verify that the constructor has put the object into the correct state? 您可以创建对象并在公共接口上使用EXPECT调用来验证构造函数是否已将对象置于正确的状态,而不是尝试测试类的实现细节?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM