Let's say I have a simple action in my controller that ends with:
render(contentType: "text/json") {
message = 'some text'
foo = 'bar'
}
It renders correctly, as per the JSON builder documentation. However, when I attempt to unit test that response in a ControllerUnitTest, I get a blank string with controller.response.contentAsString. I even tried controller.renderArgs, but that just contains contentType: "text/json".
When I convert the JSON to a map, and marshall it as JSON, then I can test properly. But is there a way to unit test the code as it stands?
you have to call the action in your tests and compare the results using controller.response.contentAsString
so your test method would look like
void testSomeRender() {
controller.someRender()
assertEquals "jsonString", controller.response.contentAsString
}
Take a look at this blog post http://www.lucasward.net/2011/03/grails-testing-issue-when-rendering-as.html
After much searching, I found that this is not possible in 1.3.7. Either have to upgrade to Grails 2.0, or override the controller metaClass as suggested in this post:
controller.class.metaClass.render = { Map map, Closure c ->
renderArgs.putAll(map)
switch(map["contentType"]) {
case null:
break
case "application/xml":
case "text/xml":
def b = new StreamingMarkupBuilder()
if (map["encoding"]) b.encoding = map["encoding"]
def writable = b.bind(c)
delegate.response.outputStream << writable
break
case "text/json":
new JSonBuilder(delegate.response).json(c)
break
default:
println "Nothing"
break
}
}
Related
I have a controller that on the save method calls a thread to retrieve some files. The thread has start() in a domain that has this line-
RetrievalThread retrievalThread = grailsApplication.mainContext.getBean ('retrievalThread').
In my unit test I tried this and it worked(I'll keep the other lines omitted that have no bearing right now). Without this line an error occurs saying can't get mainContext on null object,talking about grailsApplication. .
Def mainContext = Mock(ApplicationContext)
MainContext.getBean(_) >>{ name ->
return new MockRetrievalThread()}
The mock thread doesn't do anything.
This test runs fine but, any test after this fail with a null pointer exception with no real information. Looks like a bunch of background grails stuff. Is there a way to clean this up or use something better than what I'm using?
I'm sure there's a way to clean this up in a tearDown, but I think there is a better way.
1.) I would use DI rather than going through grailsApplication.mainContext.getBean; is there a reason you are doing it this way?
class MyController {
def retrievalThread
getFiles() {
return [files: retrievalThread.getFiles(params.id)]
}
}
2.a.) Using DI, you can then just set the controller's retrievalThread to a new instance of MockRetrievalThread within your test.
void "test getFiles"() {
given:
controller.retrievalThread = new MockRetrievalThread()
when:
params.id = 1
def returnedFiles = controller.getFiles()
then:
// assertions
}
2.b.) Or skip the MockRetrievalThread altogether and mock the retrievalThread bean using the mockFor method, and then set the mocked version to the injected instance in your controller.
void "test getFiles"() {
given:
def retrievalThreadMock = mockFor(RetrievalThread)
retrievalThreadMock.demand.getFiles { Integer input ->
return ['file1', 'file2', 'etc.']
}
controller.retrievalThread = retrievalThreadMock.createMock()
when:
params.id = 1
def returnedFiles = controller.getFiles()
then:
// assertions
}
You can use integration testing instead to run the entire app, in order to avoid any beans not being injected.
grails create-integration-test org.bookstore.Book
I have been trying to figure this out for 2 days now and I am really stuck and frustrated. I have a domain object with a service which is being used for custom validation. The domain looks like this:
class Llama {
String name
transient myFetcherService
static transients = [
'myFetcherService'
]
static constraints = {
name validator: { val, obj ->
if (obj.nameExists(val) == true) {
//return some error here.
}
}
}
protected boolean nameExists(String name) {
List<Llama> llamasList = myFetcherService.fetchExistingLlamasByName(name)
if (llamasList.isEmpty()) {
return false
}
return true
}
}
Now, I have another Service, which simply saves a list of Llama objects. It looks like this:
class LlamaFactoryService {
public void createLlamas(List<String> llamaNames) {
llamaNames.each { name ->
new Llama(name: name).save()
}
}
}
In my test. I keep getting this error:
Failure: createLlamas should create Llammas (com.myLlamaProject.LlamaFactoryServiceSpec)
| java.lang.NullPointerException: Cannot invoke method myFetcherService on null object
I don't understand. In my tests, added a metaClass for the service in the "given" section. When it tries to save, it's telling that the service is null. This is what my test looks like:
given:
def myFetcherService = mockFor(MyFetcherService)
myFetcherService.demand.fetchExistingLlamasByName {def name -> return []}
Llama.metaClass.myFetcherService = myFetcherService.createMock()
when:
service.createLlamas(['Pablo','Juan','Carlos'])
then:
//some validations here....
I also tried using metaClass on the method nameExists() like:
Llama.metaClass.myFetcherService = { def name -> false }
, but it gives me the same nullPointerException as the one above. Could someone point me to the right direction? I'm a bit stuck. :(
Thanks in advance for reading and helping.
You're using a unit test and the general rule for unit tests is that beans generally aren't created for you, so you'll need to inject them yourself.
(Code edited to reflect the fact I misread the question)
I think you want a testing pattern something like:
given:
def mockMyFetcherService = Mock(MyFetcherService) // create the mock
Llama.metaClass.getMyFetcherService = { mockMyFetcherService } // inject the dependency
def returnList = [] // let's just define this here and you can re-use this pattern in other tests more easily
when:
service.createLlamas(['Pablo','Juan','Carlos'])
then:
// tell Spock what you expect to have happen with your Mock - return the List you defined above
3 * mockFetcherService.fetchExistingLlamasByName(_) >> returnList
If the injection of the service into the metaClass doesn't work (suggested here), you could always try using the defineBeans{} closure within the unit test itself (http://www.block-consult.com/blog/2011/08/17/inject-spring-security-service-into-domain-class-for-controller-unit-testing/).
Thus you could try:
defineBeans {
myFetcherService(MockMyFetcherService)
}
where MockMyFetcherService is defined in the same file that defines the test. This is the approach followed here:
See here for examples of more Spock interactions.
If you're using Grails 2.4.3 or below you'll need to put CGLIB in BuildConfig.groovy but I see here that it's already done for you in 2.4.4, so you should be ok just to use Mock(classname).
Grails 2.3.10.
How can I configure the available mime types for content type negotiation in a Grails Spock test?
When I try to tell the controller to produce JSON content, it seems to want to return an HTTP 406 error. I send in the Accept header in my test code; but, the parser is not able to match it because HTML is the only MIME type that's configured.
My use case...
I have implemented a controller action using the Grails respond method which can return a JSON response. When I hit the endpoint using a REST API call, I am able to get back JSON output (even if no Accept header is specified).
The controller code:
#Transactional(readOnly = true)
class MyObjectController {
static allowedMethods = [save: 'POST']
static responseFormats = ['json']
def myService
#Transactional
def save(MyObject obj) {
obj.validate()
if (obj.hasErrors()) {
respond obj.getErrors(), [status: BAD_REQUEST]
}
myService.addNewCustomer(obj)
respond obj, [formats: responseFormats]
}
}
And my test code:
#TestFor(MyObjectController)
class MyObjectControllerSpec extends Specification {
def setup() {
}
def cleanup() {
}
void "test save - json success"() {
given:
def myObj = new MyObject()
controller.myService= Mock(MyObjectService)
when:
request.addHeader "Accept", "application/json"
controller.save(individual)
then:
response.status == HttpStatus.CREATED.value()
response.text == "{}" //.text is giving me an empty string
response.json.x == x //.json throws an exception (parsing an empty string)
}
}
I have verified in the debugger that obj has a valid value and that the respond method is invoked on the last line of the controller action.
What I am finding is that inside the Grails ResponseMimeTypesApi class, the DefaultAcceptHeaderParser is getting constructed with only the HTML mime type. Even though the JSON accept header is being read correctly, the DefaultAcceptHeaderParser isn't able to understand it because no mime types are configured.
How do I control the mime types that get sent to ResponseMimeTypesApi in my unit test spec?
Edit
I have also tried setting the response.format property, as suggested in this answer; but, to no avail.
If you assign a value to request.json that will set the content type. You can also set the content type explicitly with something like request.contentType = 'application/json' or request.contentType = JSON_CONTENT_TYPE. For a list of the content type constants available in your unit tests see the "Testing Mime Type Handling" section under http://grails.org/doc/latest/guide/testing.html#unitTestingControllers.
Another resource to look at is the unit tests at https://github.com/grails/grails-core/blob/4f8d1a605cde60a4a00021102959578dae8bc5a8/grails-test-suite-web/src/test/groovy/org/codehaus/groovy/grails/web/binding/json/JsonBindingSpec.groovy and https://github.com/grails/grails-core/blob/801d507cf3fec5866baa14f6d6b0acd05aa5fb56/grails-test-suite-web/src/test/groovy/org/codehaus/groovy/grails/web/binding/xml/XmlBindingSpec.groovy.
I hope that helps.
EDIT:
To clarify...
I mentioned assigning a value to request.json. The value you assign to that of course is JSON, not the content type. Like this...
request.json = '''
{
"name": "Douglas", "age": "42"
}
'''
When you do that, the content type gets set automatically.
I found that I could write the test that I wanted by converting from a unit to an integration test.
Move the test to the /integration path.
Change the test spec to extend IntegrationSpec
#Autowire the class under test instead of using #TestFor:
Set controller.response.format = 'json' and call controller.request.addHeader 'Accept', 'application/json'
Say I've got a controller with an action that receives two parameters.
It invokes two services, one with each parameter, the services both return strings
each of those strings are passed as arguments to a template
the result is passed to Ok and returned.
I want to write a simple unit test that ensures:
1 - The correct services are invoked with the correct parameters
2 - The return values from the services are passed to the correct attributes of the template
What is the best way to do that?
Using Mockito with Specs2, I mock services to verify their method calls.
My controller is instantiated by Spring. That allows me to treat it is as a class instead of object. => That is essential to make controller testable. Here an example:
#Controller
class MyController #Autowired()(val myServices: MyServices) extends Controller
To enable Spring for controllers, you have to define a Global object, as the Play! documentation explains:
object Global extends GlobalSettings {
val context = new ClassPathXmlApplicationContext("application-context.xml")
override def getControllerInstance[A](controllerClass: Class[A]): A = {
context.getBean(controllerClass)
}
}
My unit test doesn't need Spring; I just pass collaborators (mocks) to constructor.
However, concerning the rendered template, I test only for the type of result (Ok, BadRequest, Redirection etc...).
Indeed, I noticed it's not easy at all to make my test scan the whole rendered template in details (parameters sent to it etc..), with only unit testing.
Thus, in order to assert that the right template is called with the right arguments, I trust my acceptance tests running Selenium, or a possible functional test, if you prefer, to scan for the whole expected result.
2 - The return values from the services are passed to the correct
attributes of the template
It's pretty easy to check for that..How? By trusting compiler! Prefer to pass some custom types to your template instead of simple primitives for instance:
phone: String would become: phone: Phone. (a simple value object).
Therefore, no fear to pass the attributes in a non-expected order to your template (in unit test or real production code). Compiler indeed will warn.
Here's an example of one of my unit test (simplified) using specs2:
(You will note the use of a wrapper: WithFreshMocks).
This case class would allow to refresh all variables (mocks in this case) test after test.
Thus a good way to reset mocks.
class MyControllerSpec extends Specification with Mockito {
def is =
"listAllCars should retrieve all cars" ! WithFreshMocks().listAllCarsShouldRetrieveAllCars
case class WithFreshMocks() {
val myServicesMock = mock[MyServices]
val myController = new MyController(myServicesMock)
def listAllCarsShouldRetrieveAllCars = {
val FakeGetRequest = FakeRequest() //fakeRequest needed by controller
mockListAllCarsAsReturningSomeCars()
val result = myController.listAllCars(FakeGetRequest).asInstanceOf[PlainResult] //passing fakeRequest to simulate a true request
assertOkResult(result).
and(there was one(myServicesMock).listAllCars()) //verify that there is one and only one call of listAllCars. If listAllCars would take any parameters that you expected to be called, you could have precise them.
}
private def mockListAllCarsAsReturningSomeCars() {
myServicesMock.listAllCars() returns List[Cars](Car("ferrari"), Car("porsche"))
}
private def assertOkResult(result: PlainResult) = result.header.status must_== 200
}
So, I came up with a cake pattern and mockito based solution:
given the service:
trait Service {
def indexMessage : String
}
trait ServiceImpl {
def indexMessage = {
"Hello world"
}
}
Then the controller looks like:
object Application extends ApplicationController
with ServiceImpl {
def template = views.html.index.apply
}
trait ApplicationController extends Controller
with Service {
def template: (String) => play.api.templates.Html
def index = Action {
Ok(template("controller got:" + indexMessage))
}
}
And the test looks like:
class ApplicationControllerSpec extends Specification with Mockito {
"cake ApplicationController" should {
"return OK with the results of the service invocation" in {
val expectedMessage = "Test Message"
val m = mock[(String) => play.api.templates.Html]
object ApplicationControllerSpec extends ApplicationController {
def indexMessage = expectedMessage
def template = m
}
val response = ApplicationControllerSpec.index(FakeRequest())
status(response) must equalTo(OK)
there was one(m).apply(Matchers.eq("controller got:" + expectedMessage))
}
}
}
I had a lot of trouble getting Mockito working.
It requires an extra dependency and I had a lot of trouble working out how to use the matchers in scala (I'm quite comfortable using it in java)
Ultimately I think the above answer is better, avoid using String and other primitive types where you can wrap them in task specific types, then you get compiler warnings.
Also I would generally avoid doing things like the "controller got:" prefixing in the controller.
It's there in this case so I can verify that it went through, in the real world that should be done by some other component (controllers are just for plumbing IMO)
I've got a service, which is using sendJMSMessage method which is provided by jms-grails plugin.
I want to write some unit tests, but I'm not sure how to "mock" this method, so it just does nothing at all.
Any tips?
You can metaClass the method to have it return whatever you want.
#Test
void pluginCode() {
def myService = new MyService()
def wasCalled = false
myService.metaClass.sendJMSMessage = {String message ->
//I like to have an assert in here to test what's being passed in so I can ensure wiring is correct
wasCalled = true
null //this is what the method will now return
}
def results = myService.myServiceMethodThatCallsPlugin()
assert wasCalled
}
I like to have a wasCalled flag when I'm returning null from a metaClassed method because I don't particularly like asserting that the response is null because it doesn't really assure that you're wired up correctly. If you're returning something kind of unique though you can do without the wasCalled flag.
In the above example I used 1 String parameter but you can metaClass out any number/type of parameters to match what actually happens.