开发者

EasyMock condition and logic

开发者 https://www.devze.com 2023-03-02 01:08 出处:网络
Is there anyway to make EasyMock to work with condit开发者_Python百科ionals? I have an if-else block in my method but the test only passes if I remove the conditional block. This might be a poblem wit

Is there anyway to make EasyMock to work with condit开发者_Python百科ionals? I have an if-else block in my method but the test only passes if I remove the conditional block. This might be a poblem with JUnit not EasyMock specifically. Anybody has any info on this?


If I understand correctly your question you want to return different values depending of a variable. The best way of doing that is by using the IAnswer interface.

Let's say you have a DAO class getting a Color from a Point:

public class ColorDAO {
   public Color getColorFromPoint(Point point) {
       //Implementation
   }
} 

You can create an answer for that:

ColorDao colorDao = EasyMock.createMock(ColorDao.class);
EasyMock.expect(colorDao.getColorFromPoint(EasyMock.anyObject(Point.class))).andAnswer(new IAnswer<Color>() {    
         @Override
         public Color answer() throws Throwable {
            Point point = (Point) EasyMock.getCurrentArguments()[0];
            if (point .getX() > 0.0) {
               return Color.BLACK;
            }
            return Color.YELLOW;
         }
      });
EasyMock.replay(colorDao);

Hope that helps ;)


Is the condition in the test or the method being tested?

If it's in the test you could have a helper that sets up your expectations dependent on input or you could have expectations for various inputs. Neither of these depend on the behavior of the method being tested.

If it's in the method being tested then the way that you set up the expectations is not affected by the method being tested and you would need to set up expectations for your mock's behavior like normal.

0

精彩评论

暂无评论...
验证码 换一张
取 消