How to do reset mock

346 views
Skip to first unread message

Senthil V.Sundaram

unread,
Mar 19, 2013, 9:43:12 AM3/19/13
to specs2...@googlegroups.com
Hi,

This could be really simple, I assume.

"A test" should {  
 "pass" in  {
      val mockSettings = mock[Settings.type]
      mockSettings.apply("inbox_path") returns ("SOME DIFFERENET VALUE")
      ........

     //How to do reset the mock?
    }
}

Settings is a scala object.

Can u help with guiding how to reset the spec2 mock?

Thanks.

Thomas Sant'ana

unread,
Mar 19, 2013, 1:45:36 PM3/19/13
to specs2...@googlegroups.com
I thing you got the basics there. However mocking Objects can be a bit trick. First off somewhere in your code you are going to call


val inbox = Settings("inbox_path")

This does not use the mocked object, it will use the real object. 

So the way I do it is the following: 
1) Create a Setting trait that has all the methods
2) Something like

object Setting {
    def getCurrent: Setting = {
         // return an instance setting
    }
    def setInstance(newSetting: Setting) {
    }
}
    
So now on the Test you mock the trait and inject it in your object:

"show have inbox" in {
     val mS = mock[Setting]

     ms.appy("inbox_path") returns ("Value for this test")
     Setting.setInstance(mS)
     do_test()
}

In do_test() you can call like this:

    Setting.getInstance("inbox_path")
 
Now since its just a trait it's easy to mock. You still avoid dependency injection.

This is how I've done it.

Other way is to pass the Setting train to the constructor of the object and have a default that grabs setting like this:

class SomeConfiguredObject(setting: Setting) {
    def this() = this(Setting.getInstance)
}

Thomas


--
You received this message because you are subscribed to the Google Groups "specs2-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to specs2-users...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages