简体   繁体   中英

Mocking a simple method inside Service class in Grails

i was trying to mock a method (passwordComplexityCheck) which is inside UserService class.

Below is what i did for mocking in my test class

def userService
controller.userService=new UserService()

controller.userService=[passwordComplexityCheck:{def k->
   return true
}]

But this is not working.

Below is the UserService class and the method.

class UserService {
   //required declaration 
   ........
   public boolean passwordComplexityCheck(String password) {

      log.debug("Enter(Method) - passwordComplexityCheck()")

      if (password != null && password.trim() != "") {
         if (password.length() < grailsApplication.config.user.password.min.length) {
            return false
         }
         if (password == password.toLowerCase()) {
            return false
         }
         if (password == password.toUpperCase()) {
            return false
         }
         if (password.grep(~/\d+/).size == 0) {
            return false
         }
      } else {
         return false
      }
      return true
   }
}

I just need to mock this in a way that it can return either return true or false. Since the method has an argument, mocking will be different? What is the general way for mocking methods in services?

So that the in-built logging in Grails works during testing you will have to mock the logging functionality. To do this you want to include the code below in your test class. The best place is in the setUp() method before any of your code gets called.

mockLogging(UserService, true)

See: http://grails.org/doc/latest/api/grails/test/GrailsUnitTestCase.html#mockLogging%28java.lang.Class,%20boolean%29

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