Reputation: 3651
I have a method I want to test in my site
public boolean syncUser(username, password){
if (getUserFromDB(username)){
// do work
return true
}
return false
}
How do I test syncUser
and stub/mock out getUserFromDB
?
I've tried everything including
_ * _.getUserFromDB(*_) >> true
But it keeps trying to hit the method instead of using the return value. The test case is as follows:
void "successfulSyncUser"(){
given:
_ * _.getUserFromDB(*_) >> true
when:
def syncUserResult = userManagement.syncUser(username, password)
then:
syncGuidResult == true
}
Upvotes: 1
Views: 1764
Reputation: 9072
You only can use this statements on mocks.
_ * _.getUserFromDB(*_) >> true
That means you would have to first use
def mock = Mock(YourClass)
In your case getUserFromDB
and syncUser
belong to the same class. In that case you cannot use mocks.
Here is want you can do. You can use the Groovys Metaclass to override the implementation of your current UserManagement
instance.
void "successfulSyncUser"(){
given:
userManagement.metaClass.getUserFromDB = { param1 -> return true }
when:
def syncUserResult = userManagement.syncUser(username, password)
then:
syncGuidResult == true
}
Please find a simple example how to override existing methods using Groovy Magic :)
class Person {
String sayHello() { 'Foo' }
}
def a = new Person()
def b = new Person()
println a.sayHello()
println b.sayHello()
a.metaClass.sayHello = { 'Bar' }
println a.sayHello()
println b.sayHello()
This will result in the following output:
Foo
Foo
Bar
Foo
Upvotes: 1