chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
In a nutshell (this is a much simplified representation of the problem), this is what I am trying to accomplish.

I am trying to mock out a factory class with one build() method:

  class IFactory  {

  public:

    enum class Types { TypeB, TypeC };

    virtual A * build(Types type) = 0;

  };

...

 auto fakeFactory = FAKE<IFactory>();

WHEN_CALLED(fakeFactory->build(x).Return(<something dependent on x>);

I cannot seem to find the secret sauce that allows me to pass the argument with which the faked function was called - which would ideally be a lambda that I could call in place.  Even using the Doxxx() methods with an additional context doesn\\\'t seem to handle this situation.

To use the syntax from a competing library that I have been contrasting with Typemock, I can do something like this:

        Mock<IGuidedCalStateFactory> factory;

        When(Method(factory, IFactory::build)).AlwaysDo( [&](IFactory::Types buildType)

        {

          return typeToBuild == IFactory::Types::TypeB ? new B() : new C();

        });
asked by beauchai (1.1k points)

1 Answer

0 votes

Hi beauchai,

Following are examples for private and static methods:

-----PrivateMethod-----

TEST_METHOD(ReplacingPrivateMethodCallBasedOnParameters)

{

Person person;

Address* address = FAKE<Address>();

Zombieland land;

std::string city1("Unknown");

std::string cityYork("York");

// public methods can be set as private methods too

        PRIVATE_WHEN_CALLED(address, GetCityByCountry, 

            IS<std::string>([](std::string& country) { return country.compare("US") == 0 || country.compare("UK") == 0; }

        )).Return(&cityYork);

PRIVATE_WHEN_CALLED(address, GetCityByCountry(ANY_VAL(std::string))).Return(&city1);

string firstCity = person.GetCityFromAddress(address, "US");

string secondCity = person.GetCityFromAddress(address, "UK");

string thirdCity = person.GetCityFromAddress(address, "CA");

Assert::AreEqual(0, firstCity.compare("York"));

Assert::AreEqual(0, secondCity.compare("York"));

Assert::AreEqual(0, thirdCity.compare("Unknown"));

}

-----StaticMethod-----

TEST_METHOD(ReplacingStaticMethodCallBasedOnParameters)

{

Person person;

WHEN_CALLED(Address::GetCapitalCityByCountry(ANY_VAL(string))).

DoStaticOrGlobalInstead(Zombieland::GetZombielandCapitalCity, NULL);

string zombieCapital = person.GetCapitalCity("Zombieland");

string otherCapital = person.GetCapitalCity("US");

Assert::AreEqual(0, zombieCapital.compare("GhostTown"));

Assert::AreEqual(0, otherCapital.compare("Elsewhere"));

}

You can find more of these examples at the Typemock installation folder.
answered by CoralTypemock (940 points)
...