0

I'm testing my code with gtest. In my code I'm using std::thread and I need to test the situation of exception.

How can I mock std functions?

I can't separate my test for two executables and I need some test to actually create std::thread and to have few tests that test the situation of exception.

Code:

[do someting]
try {
    ChallengeThread = std::move(std::thread(&ChallengeListener, this));
    res = SUCCESS;
  } catch (const std::system_error &err) {
    Log("Caught system_error with error: " + std::string(err.what()) + ". Fail to create ChallengeListener thread");
    res = ERR_CREATE_THREAD;
  } catch (...) {
    mLogger.LogMessage("Caught ellipsis, Fail to create ChallengeListener thread");
    res = ERR_CREATE_THREAD;
  }
[do someting else] 

Test:

EXPECT_CALL(???, thread(_, _)).Times(1).WillOnce(Throw(exception));
lior.i
  • 573
  • 1
  • 7
  • 20
  • You can't do that without changing your production code. You will need to create a [wrapper](https://stackoverflow.com/questions/889160/what-is-a-wrapper-class), [inject it](https://stackoverflow.com/questions/130794/what-is-dependency-injection) into the class that you are trying to test and only then you will be able to mock it. – Yksisarvinen Dec 30 '20 at 22:55
  • Thanks @Yksisarvinen, but unfortunately I can't change my production code for the unit tests purpose. I hoped that there could be more elegant way – lior.i Dec 31 '20 at 08:03
  • the solution that we did for now for minimum code change is to write ```STD::thread``` instead of ```std::thread``` and then define ```STD``` in ```ifdef``` to be ```std``` scope for regular run or ```treadMock``` scope for test run – lior.i Dec 31 '20 at 16:00

0 Answers0