1

I am writing my own library/class that makes use of a 3rd party library. I want to write tests for my own class, and mock the 3rd party library. In one of the tests, I want to make sure that when a function on my class is being called, another function in the 3rd party library is also begin called as well. I though the FakeIt library would be a good idea to test this.

This is a sample of my testing code:

#include "MyTest.h"
#include "fakeit.hpp"

using namespace fakeit;

int main() {
    MyTest dt;
    Mock<ExternLib> mock;
    Fake(Method(mock, someFunc));
    ExternLib& el = mock.get();
    dt.begin();
    Verify(Method(mock, someFunc));
    return 0;
}

When this is run though, it throws a fakeit::SequenceVerificationException with

Expected pattern: mock.someFunc( Any arguments )
Expected matches: at least 1
Actual matches  : 0
Actual sequence : total of 0 actual invocations.

So clearly, the mock didn't work and it's method wasn't called. Any idea how I can mock this class and verify that its method is being called?

MyTest.cpp just is just a simple test and will be my full library/class:

#include "MyTest.h"

MyTest::MyTest() {
    _manager = new ExternLib();
}

void MyTest::begin() {
    result = _manager->someFunc();
}

and it's header file:

#pragma once
#include "Externlib.h"

class MyTest {
    public:
        MyTest();
        virtual void begin();
        int result = 3;
    private:
        ExternLib *_manager;
};

ExternLib is a mock version of the 3rd party library. My implementation implements the bare necessities of the real interface, and the functions don't actually do anything. The implementation is actually basically just there to satisfy the #include Externlib.h statements.

This is my Externlib.cpp:

#include "Externlib.h"

ExternLib:: ExternLib() {}

int ExternLib::someFunc() {
    return 5;
}

and the header file:

#pragma once

class ExternLib {
    public:
        ExternLib();
        virtual int someFunc();
};
4

2 回答 2

1

解释fakeit::SequenceVerificationException: 使用该行Mock<ExternLib> mock;创建一个新的实例ExternLib,它永远不会被调用MyTest(因为MyTest创建它自己的实例ExternLib)。要测试调用,您可以

  • 通过将存储在您的测试中的 ExternLib 实例_manager公开或添加访问器,然后对其进行监视Mock<ExternLib> mock(MyTest._manager);或类似的)
  • 将存储的 ExternLib 实例MyTest::_manager与您的 ExternLib Mock 实例交换。

但这意味着为了可测试而暴露您的受测主题的内部运作,这可能是不希望的。

于 2021-01-02T11:05:58.443 回答
0

但是,我以前从未使用过 fake 它,当您在使 MyTest 可注入之后将 mock.get() 传递给 MyTest 时,它可能会起作用。

class MyTest {
public:
  MyTest(ExternaLib* lib) : _manager(lib) {}
}
于 2021-01-05T22:55:04.097 回答