8

How can I mock the cast operation. I have an cast operation on a dependent object , which will cast to another dependent object like

SqlMapClient sqlMapClient;
SqlMapClientImpl sqlMapClientImpl = (SqlMapClientImpl) sqlMapClient 

I'm mocking both the dependent clesses i.e SqlMapClient and SqlMapClientImpl.But I need to know how to mock cast using EasyMock.

Any help would be appreciated.

Yuval
  • 7,987
  • 12
  • 40
  • 54
user441756
  • 81
  • 2
  • 1
    The bigger question is why do you want to mock the cast operation. What is the larger thing you trying to test? – NamshubWriter Apr 22 '12 at 17:38
  • Great [XY Problem](http://xyproblem.info/). If you feel the need to downcast from the interface into a concrete implementation, it means that your current abstraction level is leaky and that's what should be modified first. – Spotted Sep 26 '16 at 07:27

2 Answers2

4

You can't mock a cast, since a cast does not result in a method call on the object.

Instead, use EasyMock Class Extension to mock the SqlMapClientImpl class, and pass a reference to that mock to the class that takes in a SqlMapClient to a SqlMapClientImpl

Note, however, that doing a downcast like that in your code is a code smell. If your production code is doing a downcast of an interface to an implementation class, then you lose all of the flexibility of using an interface. It actually can be worse than not using an interface at all, since it looks like your class depends on the interface and can therefore be used with any implementation, but in actually your class depends on one specific implementation.

NamshubWriter
  • 23,549
  • 2
  • 41
  • 59
  • This won't work if your SqlMapClientImpl is a final class.....since you can't mock out a final class. – JamesD Mar 08 '12 at 17:42
  • @JamesD the OP already said that they are mocking `SqlMapClientImpl`. If you need to do something similar with a final class, you could try to pass in a real `SqlMapClientImpl`, assuming it was cheap to construct. – NamshubWriter Apr 22 '12 at 17:37
0

The reason why we cannot cast is Easy Mock will dynamically create a class which will Implement the SqlMapClient class and it does not have any information about the Implementation class(SqlMapClientImpl) , so a cheap trick could be create a class which implement the SqlMapClient interface and extend the SqlMapClientImpl class this might work.

Sam
  • 1