简体   繁体   中英

Grails 2.0.0 mock service always returns true?

I have a service in my controller I'm trying to mock but it always returns true. The service looks like this:

def someService (x, y){...}

Then I mocked it in my controller test: mockservice.demand.someService () {-> return false }

It keeps returning true. I don't know what's wrong. I tried including the parameters but its still not returning false. How to do this?

PS: Forgive the typos, I am on my phone right now. Thanks

I'm assuming that you're using this service in an controller, and the unit test is from the controller. I'm assuming also that you read mocking collaborators in the docs.

@TestFor(MyController)
class MyControllerSpec {
  def setup() {
    def mockServiceControl = mockFor(SomeService)
    //here you limit the amount of times that the method should be called.
    mockServiceControl.demand.someService(0..1) { x, y ->
      return false
    }
    //probably you're missing to assign the attribute in the controller
    controller.someService = mockServiceControl.createMock()
  }

  void testSomething() {
    controller.action()

    //assert response

    //Then verify that the demand mocking is correct
    mockServiceControl.verify()
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM