Question

I'm just starting to use RedBean for a small PHP web page project. I am building unit tests for each of my classes. I am not sure of how to mock RedBean in my unit tests.

The question: How can I mock RedBean classes to support unit testing?

Was it helpful?

Solution

Here is what I have done. It seems to be working pretty well so far. I am able to unit test my models, and I have isolated by static RedBean function calls:

  1. I created a thin wrapper class around the RedBean static functions I am using.
  2. I pass this thin wrapper class to each of my model classes.
  3. The model classes use this thin wrapper to CRUD RedBean data.
  4. The only place with reference to RedBean directly is the thin wrapper.
  5. During my unit tests, I just mock the thin wrapper.

Here is some example test code:

$db         =  M::mock( 'BeanDatabase' );
$bean       =  M::mock( 'Bean' );
$factory    =  M::mock( 'EntityFactory' );
$term_bean  =  M::mock( 'Bean' );
$term       =  M::mock( 'Term' );

$db->shouldReceive( 'dispense' )
    ->once( )
    ->andReturn( $bean );

$db->shouldReceive( 'find_all' )
    ->once( )
    ->with( 'term', 'WHERE termcategory_id = 5' )
    ->andReturn( array( $term_bean ) );

$factory->shouldReceive( 'create_entities_from_beans' )
    ->once( )
    ->with( array( $term_bean ) )
    ->andReturn( $term );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top