Throw Behavior

Top  Previous  Next

You can simulate exceptions using Isolator++ Professional quite easily using CallTo in combination with WillThrow(). This is helpful when you want to check your error handling code.

In the following example, we'll simulate an exception thrown when GetAgeFromFile is called:

 

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); 

}

 

 

Note: You can throw any exception as long as it is actually thrown within the code.

 

Below is an example that throws an std::exception:

 

TEST_F(Examples, Throwing)

{

   // Arrange

   auto a = Isolator();  

   Person* livePerson = new Person();

   std::exception problem("Something has definitely gone wrong!");

  

   a.CallTo(livePerson->GetAgeFromFile()).WillThrow(problem);

 

   // Act

   auto result = livePerson->GetAge();  

 

   // Assert

   ASSERT_EQ(-1, result); 

}

 

 

Note: To catch an exception in the test thrown in an Original behavior of a method on a 64-bit system in your test, use the HandleExceptionInTest flag. For more details, see Handling Exceptions thrown by fakes.

 


Copyright  Typemock Ltd. 2009-2025.  All Rights Reserved.