marcoL
marcoL

Reputation: 23

Asserting a changed state on a mocked object

I would like to unit test a function that takes a certain object as input, processes it and when it finished, the state of that object should have been changed to a certain value.

As I want to do "real" unit testing (as I understand it), I only want to use the class that is providing the processing function, and mock all other classes used. To fulfill this requirement I need to mock the object that is being processed; but when it is only a mock, it has no real state anymore that could be changed.

Example pseudocode:

object = createMock('SomeClassName');
object.whenReceives('getState').shouldReturn(0);

Processor.process(object);
assertEquals(expected = 1, actual = object.getState());

The problem is that I need to mock the "getState" method to prepare the starting state for the test, and so afterwards I cannot use the real method anymore. Do you know how can I achieve this, or how I should change the design of the test?

PS: I am actually using PHPUnit and Mockery.

Thank you for any advice.

Upvotes: 2

Views: 521

Answers (1)

Matteo
Matteo

Reputation: 39420

You are not deal with real object so you don't ask to the object the changed value but you can assert that someone dial with it for change the state. As Example:

$mock = Mockery::mock($class);


// Check that someone call the getstate method only one time
$mock
    ->shouldReceive('getState')
    ->once()
    ->andReturn(0);


// Check that someone call change the state method
$mock
    ->shouldReceive('setState')
    ->once()
    ->with(1);

Further reference:

http://code.tutsplus.com/tutorials/mockery-a-better-way--net-28097

http://culttt.com/2013/07/22/getting-started-with-mockery/

hope this help

Upvotes: 1

Related Questions