views:

104

answers:

1

I'm currently writing a wrapper of the Spotify Metadata API to learn Scala. Everything's fine and dandy but I'd like to unit test the code. To properly do this I'll need to stub the Spotify API and get consistent return values (stuff like popularity of tracks changes very frequently).

Does anybody know how to stub web calls in Scala, the JVM in general or by using some external tool I could hook up into my Maven setup?

PS I'm basically looking for something like Ruby's FakeWeb...

Thanks in advance!

+3  A: 

Sounds like you need a mocking framework to stub out the web-related calls (and layer your software appropriately to plug in either the real web framework or your mocked equivalent). JMock and Mockito both work well.

You'll need to use them in conjunction with a test framework such as Junit or TestNG. I've used all of these with Scala and they work as expected.

Brian Agnew
Thanks Brian! I know how to stub calls I do inside the unit test with JMock and Mockito, the problem however is that I want to stub a call that is made inside the method I'm testing. I make a call to a method which internally does an HTTP call. I want to stub that internal HTTP call.
Dennis Laumen
Agree with @Brian on JMock or Mockito (though I would use them with Specs (http://code.google.com/p/specs/) - this testing approach seem to be more Scalish). >>> "I make a call to a method which internally does an HTTP call." >>> Then you need to mock that internal object you use for making a call.
Vasil Remeniuk
Thanks Vasil! Could anyone explain to me how to mock an internal object? I know how to use Mockito or JMock on a basic level (mocking an object and stubbing some methods) but have no experience mocking internal objects or classes. Any help would be appreciated!
Dennis Laumen
@Dennis It seems what you need is Dependency Injection. Your inability to test the code seems to be a sign of high coupling, or of doing too much inside a single class. If you use a dependency framework such as Guice to get the internal object instantiated, then mocking it will become easy.
Daniel
Thanks for your comment Daniel! I've considered using a Dependency Injection framework but for a project this small it 'feels' like overkill. I would basically introduce a DI framework to inject my HTTP library (Databinder Dispatch). I would consider that overkill and an unnecessary dependency (although the necessity of the dependency is of course up for discussion ;)).
Dennis Laumen
I'm considering defining a trait which does the HTTP calls. Maybe a test trait with a stubbed HTTP call would be possible. I'm at work right now so I'll see if it's possible tonight.
Dennis Laumen