

package gov.va.med.cds.testharness.examples;


import gov.va.med.cds.junit.runners.SuiteAwareRunner;
import gov.va.med.cds.junit.runners.Suite;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;


/**
 * Examples of how to use mock objects in unit tests
 */
@RunWith( SuiteAwareRunner.class )
public class MockObjectTest
{
    SomeClass classToTest = null;
    CalculatorInterface mock = null;


    @Before
    @Suite( groups = "checkintest" )
    public void beforeMockObjectTestMethod( )
    {
        classToTest = new SomeClass();
        mock = EasyMock.createMock( CalculatorInterface.class );
        classToTest.setCalculator( mock );
    }


    /**
     * Demonstrates the use of a mock object
     * @throws Exception
     */
    @Test
    @Suite( groups = "checkintest" )
    public void testSimpleMock( )
        throws Exception
    {
        EasyMock.expect( mock.calculate( 1 ) ).andReturn( 2 );
        EasyMock.replay( mock );
        Assert.assertEquals( 2, classToTest.figureItOut( 1 ) );
    }


    /**
     * Demonstrates the use of a mock object with an expected exception
     */
    @Test( expected = Exception.class )
    @Suite( groups = "checkintest" )
    public void testSimpleMockExpectException( )
        throws Exception
    {
        EasyMock.expect( mock.calculate( 1 ) ).andThrow( new Exception() );
        EasyMock.replay( mock );
        Assert.assertEquals( 2, classToTest.figureItOut( 1 ) );
    }
}


interface CalculatorInterface
{
    boolean isValid( int someNumber );


    int calculate( int someNumber )
        throws Exception;
}


class SomeClass
{
    private CalculatorInterface calculator = null;


    public int figureItOut( int someNumber )
        throws Exception
    {
        return calculator.calculate( someNumber );
    }


    public void setCalculator( CalculatorInterface dependant )
    {
        this.calculator = dependant;
    }
}