unit-testing,grails , Grails 2.4.4 generated controller test fails

Grails 2.4.4 generated controller test fails


Tag: unit-testing,grails

I have test for the save action of a controller. It just executes the action with correct params, but the problem is on the redirectedUrl line: it is null.

Using the app, after saving the domain instance, I get the redirection to the show action and the show view is rendered correctly.

Any clues of what's the problem here?

The controller:

@Transactional(readOnly = true)
class FolderController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def save(Folder folderInstance) {

        if (folderInstance == null) {

        if (folderInstance.ehrId)
           def ehr = ehr.Ehr.get(folderInstance.ehrId)
           ehr.directory = folderInstance

        if (folderInstance.hasErrors()) {
            respond folderInstance.errors, view:'create'

        folderInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'folder.label', default: 'Folder'), folderInstance.id])
                redirect folderInstance
            '*' { respond folderInstance, [status: CREATED] }

The test:

class FolderControllerSpec extends Specification {

    void "Test the save action correctly persists an instance"() {

        when:"The save action is executed with a valid instance"
            def folder = new Folder(params)

            println folder.errors // no errors

        then:"A redirect is issued to the show action"
            response.redirectedUrl == '/folder/show/1'
            controller.flash.message != null
            Folder.count() == 1

The output:

junit.framework.AssertionFailedError: Condition not satisfied:

response.redirectedUrl == '/folder/show/1'
|        |             |
|        null          false
org.codeh[email protected]112b2f1

    at directory.FolderControllerSpec.Test the save action correctly persists an instance(FolderControllerSpec.groovy:61)


I forgot to add the allowedMethods field.

The first problem was that the generated tests doesn't sets the right request method for the correspondent actions, so to call .save() this is needed: controller.request.method = "POST"

Then what @user1690588 suggested (request.format = 'form') did the trick to get the right redirectedUrl.

My final test looks like this:

void "Test the save action correctly persists an instance"() {

    when:"The save action is executed with a valid instance"
        def folder = new Folder(params)

        controller.request.method = "POST"
        request.format = 'form'


    then:"A redirect is issued to the show action"
        response.redirectedUrl == '/folder/show/1'
        controller.flash.message != null
        Folder.count() == 1


Testing beforeFilter() function

I am doing unit testing for a PHP application using CakePHP framework. The function that I am testing is beforeFilter() which basically loads the models. public function beforeFilter(Event $event) { parent::beforeFilter($event); $this->loadModel('Model1'); $this->loadModel('Model2'); $this->loadModel('Model3'); $this->loadModel('Model3'); } How should I test this function ? What assertions I need to make in...

How detailed should your repository be? Testing issues [closed]

In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

Log Grails Pre 3.0 startup time

In Grails 2.x.x is it somehow possible to log the startup time? We are currently trying to optimize the application startup and having the startup time logged would help tremendously.

How to unit test a data extraction method

I have created a method which interacts with a framework, pulling out order items which have a completed status. However, how can I unit test my method to ensure it behaves correctly... class A { public function extractData() { // extract data from framework $dataCollection = FrameworkX->getDataCollection('sales/orders'); $dataCollection->filter('state', 'complete'); return...

Dependency injection in JavaScript using apply, call or bind methods

I'm fairly new to JavaScript and have a question about unit-testing an object and it's methods. Is using the JavaScript bind, apply and call methods considered a form of dependency injection? I ask because I have several functions I want to unit-test that use the 'this' keyword and I would...

Selenium C# Element Not Found Taking a Long Time

I am using Selenium for C# to test a page. Is there a way to quickly fail if the element is not found on the page? I am experiencing if the HTML element is not found on the page the Selenium test a very long time and then eventually it...

How do I mock multiple levels of DbSet.Include lambdas?

I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

unable to resolve class org.apache.commons.net.ftp in grails

I am developing a module in which some file need to be uploaded on a ftp server for that I have added the "commons-net-3.3.jar" in my grails app & while using it import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPClientConfig import org.apache.commons.net.ftp.FTPFile import org.apache.commons.net.ftp.FTPReply It is throwing the error unable to resolve...

Rspec view test with url parameters

I have a page dashboard.html.erb that may be redirected to from several different controllers/actions. When it receives the redirect, it also receives several url parameters. Controller code: class PlansController def some_action redirect_to dashboard_path(show: "default", cool_array: ["test", "test"]) end end class StaticpagesController def dashboard end end View code: <% if cool_array...

Groovy - timestamp from minutes

I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

How to mock a Android NFC Tag object for unit testing

I'm currently working on an Android project which needs NFC integration. Now I want to write some (j)unit tests to see if the application can receive NFC intents (specifically ACTION_TECH_DISCOVERED) and put the given tag (in NfcAdapter.EXTRA_TAG) on a bus system. However to my surprise I cannot create a Tag...

Unit Testing Synchronous Method With Code Calling Task

Given the following class: public class TestAttribute : ActionFilterAttribute { public bool SomeExampleBool = false; public override void OnActionExecuting(HttpActionContext actionContext) { Task.Factory.StartNew(() => { SomeExampleBool = true; }); } } How would you write a valid unit test for OnActionExecuting that Asserts that SomeExampleBool is equal to true? When writing...

nose reports cumulative coverage

Image a situation where you have a BASE_CLASS. Several class inherits from that class: CHILD_A, CHILD_B, CHILD_C. Now let us write unit tests, but ONLY for CHILD_A, CHILD_B, CHILD_C. I would suspect, that the coverage for BASE_CLASS is 0%. Unfortunately, nose takes cumulative coverage, which is not what I want....

[B cannot be cast to java.sql.Blob

This is my domain class class TimesheetSubmission { Date submissionDate=new Date() String foreman String shift String jobId Date date byte[] xmlSubmission String xmlResponse static constraints = { submissionDate nullable: false foreman nullable: false shift nullable: false jobId nullable: false date nullable: false xmlSubmission nullable: true xmlResponse nullable: false } static...

Unit Testing VSTO projects

In most unit test tutorials I follow it has me create a second unit test project and then add a solution/project reference from the test project to the other project. I have a VSTO addin, and when I go to add the reference I don't see anything listed under Solution...

Why are nUnit tests just getting ignored when using TestCaseSource?

I am having a lot of difficulty getting the nUnit TestCaseSource attribute to work correctly in nUnit When running the unit tests through VS2010, it just says the tests are being ignored, without any additional information as to why. The Create test just appears greyed out on the test...

Visual Studio C# Unit Tests

I'm trying to learn Unit Testing in C#. But I don't see how to relate the testmethods to the actual methods. In one guide it told me to right click the method name and click create unit test. I don't see that. Another told me to create a Unit Test...

Render a controller into a String

I can render a template or a view into a String, but how can I render a controller into a String ? I would like to perform this kind of operation: def myAction = { ... def html = renderToString(controller: 'myController', action: 'myAction', params: [what:'ever']) render modify(html) ... } ...

Can I pass VisualStudio Edition name through a compiler option?

I am using Microsoft.QualityTools.Testing.Fakes to mock some unit tests. But this assembly is only available to users with VisualStudio Ultimate. Users with other editions (Professional) can't build and run this test project, and it gives an error on their environments. So I have created a compiler directive to deal this:...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline

Since there is no deferred option for: <asset:javascript src="custom_view_script.js"/> What else can be used, outside of resource plugin, to place view specific script right before the closing body tag and without declaring it globally in layout? I do know about: <asset:deferredScripts/> but that only handles on page script and not...

File upload with grails and jquery

I have a form with multiple inputs plus a doc or pdf file upload. //Multiple input fields are here then upload -> <div class="controls"> <div class="fileupload ${ person?.attachment ? 'fileupload-exists' : 'fileupload-new' }" id="attachment" data-provides="fileupload" data-name="attachment"> <span class="btn btn-file"> <span class="fileupload-new">Add</span> <span class="fileupload-exists">Change</span> <input type="file" /> </span> <span class="fileupload-preview"></span>...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

How to check http status code in python version agnostic way?

I'm writing python code that should run both with python 2.7 and 3.3+ I'm trying to figure out a way to properly check for http status codes and don't reduce my test coverage %. if I write something like: try: import http.client as httpclient except ImportError: import urllib as httpclient...

How to setup Request.Header in FakeHttpContext for Unit Testing

I have a FakeHttpContext I have been trying to modify to include some headers for testing purposes public static HttpContext FakeHttpContext() { var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id",...

Unit testing: bypass or mock call to static email helper

Apologies - this is a likely duplicate. But I was unable to find a useful answer elsewhere on the site. Currently working on adding email-sending functions to an application. It's not been done under TDD but we've built the tests as we go along and have good coverage. My task...

When should I use the .As method of Moq?

When exactly do we need to use the .As method provided by Moq? From the Quickstart documentation: // implementing multiple interfaces in mock var foo = new Mock<IFoo>(); var disposableFoo = foo.As<IDisposable>(); // now the IFoo mock also implements IDisposable :) disposableFoo.Setup(df => df.Dispose()); But I just don't get why...

passing backbone collection to view

I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...

configuration of karma/jasmine to test angularjs throws: No provider for “framework:jasmine”!

Hello I'm trying to implement unit-tests for angularjs with karma and jasmine. I followed therefore this tutorial: http://tech.pro/tutorial/1473/getting-started-with-angularjs-unit-testing On the point Running Your First Test I get sucked because of an error: No provider for "framework:jasmine"! I googled for it and tried the suggested things like installing karma-jasmine and karma-chrome-launcher...

grails 3.0.1 scaffolded view does not show domain relationship

I am following the example in the book "Grails a Quick-Start Guide" using Grails 3.0.1 with following domains package com.tekdays class TekEvent { static constraints = { name() city() description maxSize:5000 organizer() venue() startDate() endDate() } String city String name TekUser organizer String venue Date startDate Date endDate String description...

How to unit test the GPS location in android using Robolectric?

I have an android app that gives the current location when button is tapped. I want to unit test this functionality . I'm using Robolectric . The issue is ,the system services are accessed in onCreate() method but not out of it. If that is the case,how can I access...

alert grails pagination current offset value

I am using Grails 2.4.2. I have a list which is using pagination. When I mouse hover a number or next page icon it shows current offset number as tool tip. Can I alert this offset number or get my list's current page offset number?

Visual Studio 2012 - Fill message test result

When a test end its running i have a list like this Result1 Name: 01- AutoGenerateRequest (requestgenerationtest) Result1 Outcome: Passed Result1 Duration: 0:00:26,2924949 Result1 Message: Result1 StackTrace: how can i write something in the result message or stacktrace?...

Error when using angular with Grails

Here is my index.gsp <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src="/js/angular.min.js"></script> </html> When I build an app, There is an error like this, Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=myApp&p1=Error%3A%…20at%20d%20(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fangular.min.js%3A17%3A381)...

Grails 3.0 Searchable plugin

I've tried to use the searchable plugin in grails 3.0, but I am not sure wheather it is compatible or not. I've added compile "org.grails.plugins:searchable" to the dependencies. The build completes but yields a NotSearializableException: > Configuring > 1/1 projects > Resolving dependencies ':agent' > Resolving dependencies ': BUILD SUCCESSFUL...

How to mock a window.location function in Karma/jasmine

I would like to mock a functionality in Karma who returns a file after clicking a download button. I have the following AngularJS controller: var secure = angular.module('secure', []); secure.controller('ProcedureController', ProcedureController); ProcedureController.$inject = ['$controller', '$rootScope', '$scope', '$http']; function ProcedureController($controller, $rootScope, $scope, $http) { ... // Controller does more stuff var...

Django test RequestFactory vs Client

I am trying to decide whether I should use Django's Client or RequestFactory to test my views. I am creating my server using DjangoRESTFramework and it's really simple, so far: class SimpleModelList(generics.ListCreateAPIView): """ Retrieve list of all route_areas or create a new one. """ queryset = SimpleModel.objects.all() serializer_class = SimpleModelSerializer...

How do I stub and spy at the same time

So I'm testing a function that calls another function, that returns a promise, SUT looks like this: fn($modal) -> modalInstance = $modal.open({ controller: 'myCtrl' size: 'lg' }) modalInstance.result.then(updateData) now If I need to test it I could start with something like this: it 'when modal called, results get updated with...

Robolectric 3 : Load test specific resource

I'm using Robolectric 3 and I'm trying to load some resources that are in my test/res/ folder. Here is my file hierarchy : project/ |-src/ |--main/ |---AndroidManifest.xml |---res/ |----raw/ |-----prod.json |--test/ |---java/ |----com.app/ |-----CustomTestRunner.java |-----Mytest.java |---res/ |----raw/ |-----test.json I would like in MyTest.java to do something like RuntimeEnvironment.application.getResources().openRawResource(R.raw.test); but i...

Flask jsonify boolean response cannot be decoded in unit tests

I am performing tests on my Flask application and I am expecting a json response built with jsonify. I use the ast library to decode the response. But I am getting the following error: Traceback (most recent call last): File "test_index.py", line 177, in test_create_venue data = ast.literal_eval(rv.data) File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py",...

How can I verify that RemoveRange has been called on a mock DbContext?

I am using Moq to test code that calls RemoveRange on a DbSet<T>. I have mocked the context object and DbSet, but when I attempt to Verify that RemoveRange was called, I get "Expected invocation on the mock once, but was 0 times." The method I'm testing has this code:...

Grails logging auto inject

I use grails 3.0.2 and logback. How can I use this logger in my code, can I somehow autoinject it, like log.debug() in grails 2.x which was using org.apache.commons.logging.Log?

Grails: Do addTo* and removeFrom* require a call to save?

In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

Dependencies in Unit Tests

From what I've read on the subject, each unit test should be independent and not rely on the results or success/failure of any other test. Makes good sense to me. How best to write tests that have dependencies then? Take the simple example like a file system that has a...

NUnit Categories not showing up in Visual Studio

I want to custom group my tests by function so I'm using the nunit Category attribute, like this: [Test, Category("Cat1")] public void SomeMethod() { } [Test, Category("Cat2")] public void AnotherMethod() { } But in Visual Studio the categories do not show up, all I see are the defaults to group...

Intercepting login calls with Spring-Security-Rest plugin in Grails

I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts. As I am quite new to Spring Security...

Decode base64 image in Grails [duplicate]

This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Spock Framework: problems with spying

I have an issue with using Spy in Spock, it either doesn't work as it should or my understanding is wrong so I'm trying to clarify this. Consider this code (Java): public class CallingClass { public String functionOne() { //does stuff return "one"; } public String functionTwo() { String one...

Grails: Carry forward params on g:actionSubmit is clicked

How to carry forward the parameters when g:actionSubmit button is clicked? Here is my gsp code: <g:checkBox name="msgCheck" checked="" value="${userInstance.emailId}"></g:checkBox> ... <g:actionSubmit class="update" action="delete" value="Delete" params="${params}"></g:actionSubmit> Here is my controller code: def delete() { try { def user_list = params.msgCheck //deleting the user //successful. redirect(action: "list", params: params) } catch...

Testing a function with several side effects [on hold]

Consider this (bash) function which has several side-effects (setting a global variable, printing to stdout): describe() { printf '\n%s\n' "$1" skip_specs=false } It prints to stdout and sets the value of the global variable skip_specs. What are the pros/cons of: one test per side-effect one test for both side-effects ...

grails DataSource.groovy refer bean for decoding password

Referring https://jira.grails.org/browse/GRAILS-3620, we need to specify a class with static methods to decode the encrypted password in DataSource config. For passwordEncryptionCodec property, is it possible to refer to a bean defined in resources.xml or any other grails bean definition files? For ex: having a decrypted Properties bean in resoures.xml or...