Reputation: 9636
I have a class in src/groovy
class Something {
def foo
}
this is in resources.groovy
beans = {
mySomething(Something)
}
In my Controller I use this :
class MyController {
def mySomething
def index () {
mySomething.foo = "bar"
render mySomething.foo
}
}
How do I test this?
@TestFor(MyController)
class MyControllerSpecification extends Specification {
def "test bean"
given:
controller.mySomething = new Something() //is this the best way?
when:
controller.index()
then
response.contentAsString == "bar"
}
Question
Is this the best way to test this? I've generally seen Mocks created for classes. What is the benefit of the Mocks and should I be using them here?
Upvotes: 0
Views: 1356
Reputation: 50245
You can use defineBeans
(refer Testing Spring Beans) while setUp
or given
since Something
has been declared as a bean
inside resources.groovy
defineBeans{
mySomething(Something){bean ->
//To take care of the transitive dependencies inside Something
bean.autowire = true
}
}
Upvotes: 1
Reputation:
You use a mock implementation of your service if this is faster than creating a new instance and populating the dependencies.
Sometimes you can have a complex service, that depends on other services and the effort of setting up all required structure is high, then you can use Grails mockFor()
method and just mock the specific methods that you will use.
Grails docs show you how to mock classes that will be used in your unit test.
In your example I don't see advantages, since Something is just a holder for foo.
Upvotes: 1