3
public class Card
{

public double roundMoney(double currencyValue , int digits) {
//some logic for rounding which includes heavy service calling
} 

}

Now I want to mock the class and whenever the roundMoney methods is called with parameters I want it to return the product of the parameters

Card mycard = mock(Card.class);
when(mycard.roundMoney(anyDouble(), anyInt()).thenReturn( anyDouble() * anyInt() ));

How can I achieve this?

Joel
  • 63
  • 4
  • Err, **why**? You see, in programming, you dont do things because you CAN, but because doing so is meaningful. Test cases should be as easy to understand as possible. Like: setup some mock object, to give a specific response for a specific request. If you need more than that, why use mocks for it? And not say a test-only subclass of whatever service you are using? Meaning: what you are asking for is possible, but adds plenty of complexity to your test code. Be careful about going down that road. – GhostCat Dec 16 '21 at 19:36
  • Also note: your question very much depends on the mocking framework you are using. So: specify which framework you want to use, for example by applying the correct tag for mockito, easymock, or whatnot. – GhostCat Dec 16 '21 at 19:37

1 Answers1

1

Use thenAnswer instead of thenReturn? The answer implementation has access to the parameter values being passed.

See: Making a mocked method return an argument that was passed to it

dev101
  • 353
  • 1
  • 2
  • 9