Handling Exceptions thrown by fakes |
Top Previous Next |
Note: This feature applies to 64-bit systems only.
By default, Isolator++ Professional expects exceptions thrown from faked methods (including InvokeOriginal and WillCallOriginal) to be caught in the test code, not the under-test code. This allows for better control and assertion of exceptions during testing.
Example:
class Person {
public: int GetAge() { try { return GetAgeFromFile(); } catch { return -1; } int GetAgeFromFile() { ... } };
TEST_F(Examples, Throwing) { // Arrange auto a = Isolator(); Person* livePerson = new Person();
a.CallTo(livePerson->GetAgeFromFile()).WillThrow("File doesn't exist");
// Act auto result = livePerson->GetAge();
// Assert ASSERT_EQ(-1, result); }
In some cases, you may want the exception to be caught in the test, rather than in the under-test code. To achieve this, you must use the FakeOptions::HandleExceptionInTest flag.
For example let's test that an exception was thrown:
class Person {
public: int GetAge() { int result = GetAgeFromFile(); if (result () == -1) { throw std::exception("Exception thrown"); } return result; } int GetAgeFromFile() { ... } };
TEST_F(Examples, CatchExceptionInTest) { // Arrange auto a = Isolator(); // create a fake under test that will call all original code but exceptions will be caught in this test auto livePerson = a.Fake.Instance<Person>(FakeOption::CallOriginal | FakeOptions::HandleExceptionInTest);
a.CallTo(livePerson->GetAgeFromFile()).WillReturn(-1);
// Act (you can use ASSERT_THROWN too try { person->GetAge(); ASSERT_EQ(-1, 1); // FAIL } catch (std::exception& e) { // Assert (can check exception here) } }
|
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.