Reputation: 1022
I'm new to unit testing in Scala and I can't find a way to stub a function defined in a singleton object.
For example:
class Profile {
def getLatest
...
Feed.getLatestEntries
...
}
object Feed {
def getLatestEntries: Future[List[FeedEntry]] { /* Access some API*/ }
}
I'm trying to unit test the getLatest
function defined in the Profile class.
Since I don't want to actually access an external API through the web in my unit tests I'm trying to stub the Feed
object and its getLatestEntries
function to return some predefined value.
I've looked into the ScalaMock, EasyMock and Mockito frameworks but could not find a way to stub a method of a singleton object. ScalaMock states
How come all the mocking frameworks do not offer this functionality? How can I do this? stub Feed.getLatestEntries
?
Thanks
Upvotes: 1
Views: 2801
Reputation: 14404
My approach has been to create the logic of the singleton as a trait and then have the object extend the trait. This allows me provide the Singleton as a default or implicit argument, but provide a stubbed out implementation for testing
trait FeedLogic {
def getLatestEntries: Future[List[FeedEntry]] { /* Access some API*/ }
}
object Feed extends FeedLogic
def somethingWantingFeed(...)(feed: FeeLogic = Feed) = { ??? }
Upvotes: 5