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


Grails 2.4.4 generated controller test fails

Question:

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"]
    ...

    @Transactional
    def save(Folder folderInstance) {

        if (folderInstance == null) {
            notFound()
            return
        }

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

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

        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:

@TestFor(FolderController)
@Mock(Folder)
class FolderControllerSpec extends Specification {

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

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

            controller.save(folder)
            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)

Answer:

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"
        response.reset()
        populateValidParams(params)
        def folder = new Folder(params)

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

        controller.save(folder)

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

Related:


File upload with grails and jquery


jquery,grails
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>...

Can I pass VisualStudio Edition name through a compiler option?


c#,visual-studio,unit-testing,vs-unit-testing-framework,compiler-options
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:...

Unit Testing VSTO projects


c#,unit-testing,vsto
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...

Grails 3.0 Searchable plugin


maven,grails
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...

grails DataSource.groovy refer bean for decoding password


grails
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...

How do I stub and spy at the same time


javascript,angularjs,unit-testing,mocha,sinon
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...

How to unit test a data extraction method


php,unit-testing,phpunit
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...

Spock Framework: problems with spying


java,unit-testing,groovy,spock,spock-spy
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...

How to setup Request.Header in FakeHttpContext for Unit Testing


c#,unit-testing,asp.net-web-api,httpcontext
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",...

Rspec view test with url parameters


ruby-on-rails,unit-testing,testing,rspec,rspec-rails
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...

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


angularjs,unit-testing,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...

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


grails,gorm,grails-2.0,grails-domain-class
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?

alert grails pagination current offset value


grails,pagination
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?

Dependencies in Unit Tests


c#,unit-testing,nunit
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...

Decode base64 image in Grails [duplicate]


grails,groovy
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...

Testing beforeFilter() function


php,unit-testing,cakephp-3.0
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 do I mock multiple levels of DbSet.Include lambdas?


entity-framework,unit-testing,lambda,moq
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...

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


grails,groovy,jax-rs
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...

Flask jsonify boolean response cannot be decoded in unit tests


python,unit-testing,flask
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",...

Dependency injection in JavaScript using apply, call or bind methods


javascript,unit-testing
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...

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


c#,entity-framework,unit-testing,moq
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:...

Robolectric 3 : Load test specific resource


android,unit-testing,robolectric
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...

nose reports cumulative coverage


python,unit-testing,testing,nose
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....

Django test RequestFactory vs Client


django,unit-testing,django-views,django-rest-framework,django-testing
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...

Error when using angular with Grails


angularjs,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)...

Render a controller into a String


grails,grails-2.0
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) ... } ...

Selenium C# Element Not Found Taking a Long Time


c#,unit-testing,selenium,selenium-webdriver
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...

NUnit Categories not showing up in Visual Studio


unit-testing,visual-studio-2012,nunit
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...

Grails: Carry forward params on g:actionSubmit is clicked


grails,gsp
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...

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
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?...

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


grails,apache-commons
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...

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


grails,grails-plugin
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...

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


rest,grails,spring-security
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...

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


angularjs,unit-testing,karma-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...

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


python,unit-testing,httplib,test-coverage,http.client
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...

passing backbone collection to view


grails,backbone.js,handlebars
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...

Grails logging auto inject


grails,logback
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?

Why are nUnit tests just getting ignored when using TestCaseSource?


c#,.net,unit-testing,nunit
I am having a lot of difficulty getting the nUnit TestCaseSource attribute to work correctly in nUnit 2.6.4.14350. 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 2012 - Fill message test result


c#,asp.net,unit-testing,visual-studio-2012,testing
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?...

Log Grails Pre 3.0 startup time


grails
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 the GPS location in android using Robolectric?


java,android,unit-testing,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...

How to mock a Android NFC Tag object for unit testing


android,unit-testing,android-intent,mocking,nfc
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: bypass or mock call to static email helper


c#,unit-testing
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...

grails 3.0.1 scaffolded view does not show domain relationship


grails,scaffolding
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...

When should I use the .As method of Moq?


c#,unit-testing,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...

Unit Testing Synchronous Method With Code Calling Task


c#,.net,multithreading,unit-testing
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...

Testing a function with several side effects [on hold]


unit-testing
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 ...

[B cannot be cast to java.sql.Blob


grails,gorm
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...

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


c#,unit-testing,asp.net-mvc-5
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 =...

Visual Studio C# Unit Tests


c#,unit-testing,visual-studio-2013
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...