Java Mailing List Archive

http://www.gg3721.com/

Home » user.jmock »

[jmock-user] Re: Can I mock an enum

Avinash Nayak

2008-09-13

Replies: Find Java Web Hosting

Author LoginPost Reply
I got what you guys saying.
Understood the fact that the enums are final
and hence cant mock them using jmock rather with ClasssImposteriser.INSTANCE.
Still will try to convince what i was trying to achieve.
I am posting a code snippet. this is quite simple version of my code.

public enum Strategy {
 StrategyTrue(Boolean.TRUE), StrategyFalse(Boolean.FALSE), StrategyNone(null);

 private Boolean value;

 private Strategy(Boolean value) {
   this.value = value;
 }

 public Boolean getValue() {
   return value;
 }
}

public class MyClass {
 public Boolean myMethod(Strategy strategy) {
   return strategy.getValue();
 }
}

public class MyClassUTEST extends TestCase {
 public void test_myMethod() {
   // Mocked Value;
   final Boolean mockedValue = Boolean.TRUE;

   Mockery context = new Mockery();
   context.setImposteriser(ClassImposteriser.INSTANCE);
   final Strategy strategy = context.mock(Strategy.class);

   context.checking(new Expectations() {
     {
       oneOf(strategy).getValue();
       will(returnValue(mockedValue));
     }
   });

   assertEquals(mockedValue, new MyClass().myMethod(strategy));
   context.assertIsSatisfied();
 }
}

This way a single testcase can cover all the test scenarios of the method.
Otherwise, i would have to write test for each Enum value.
I could make it work by changing the enum in the following way.

public enum Strategy {
 StrategyTrue() {
   @Override
   public Boolean getValue() {
     return Boolean.TRUE;
   }
 },
 StrategyFalse() {
   @Override
   public Boolean getValue() {
     return Boolean.FALSE;
   }
 },
 StrategyNone() {
   @Override
   public Boolean getValue() {
     return null;
   }
 };

 public abstract Boolean getValue();
}

But still, i would have appreciated the first attempt.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

  http://xircles.codehaus.org/manage_email


©2008 gg3721.com - Jax Systems, LLC, U.S.A.