I have created a new Grails 3.1.4 angular project along with a few domain objects and controllers extending RestfulController. I have created the Integration test below. When I run grails test-app -integration I get the error
java.lang.IllegalStateException: No transactionManager was specified. Using #Transactional or #Rollback requires a valid configured transaction manager. If you are running in a unit test ensure the test has been properly configured and that you run the test suite not an individual test method.
at grails.transaction.GrailsTransactionTemplate.<init>(GrailsTransactionTemplate.groovy:60)
at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.$tt__$spock_feature_0_0(BillingEntityRestControllerIntegrationSpec.groovy:29)
at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.test all entities_closure2(BillingEntityRestControllerIntegrationSpec.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:442)
at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
at com.waldoware.invoicer.BillingEntityRestControllerIntegrationSpec.test all entities(BillingEntityRestControllerIntegrationSpec.groovy)
Test class:
package com.waldoware.invoicer
import grails.test.mixin.integration.Integration
import grails.transaction.*
import spock.lang.*
#Integration
#Rollback
class BillingEntityRestControllerIntegrationSpec extends Specification {
def setupData() {
def biller = new BillingEntity()
biller.with {
companyName = "Acme, Inc."
}
def ledger = new Ledger(name: "My Ledger", billingEntity: biller).save(failOnError: true, flush: true)
}
void 'test all entities'() {
when:
setupData()
new BillingEntityRestController().index()
then:
response.contentType == 'application/json;charset=UTF-8'
response.status == HttpServletResponse.SC_OK
response.text == "[{}]"
}
}
I do have a datasource set up in application.yml:
environments:
development:
dataSource:
dbCreate: none
url: jdbc:h2:./devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
test:
dataSource:
dbCreate: update
url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
production:
dataSource:
dbCreate: update
url: jdbc:h2:./prodDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
This can help if you do not have a persistence plugin configured in your build.gradle that sets up a transaction manager (examples include hibernate4, mongodb, neo4j etc. or you do not have a dataSource configured in grails-app/conf/application.yml.
If this is the case, simply remove the #Rollback annotation and that should fix the problem.
Ran across this while troubleshooting my own integration test. I resolved my problem by deleting the out directory.
delete project-folder/out/
Now you'll also need to clean and rebuild a war file. This must run some extra steps in the build process and resolves some issues
./grailsw clean
./grailsw war
Now when you run your tests you shouldn't see the error message.
Related
I am usgin Laravel 9 test tool.
I dropped the database, recreated and imported using SQL statement.
With all the database set, I used the browser to log in with my user, and everything worded just fine.
Then I ran the php artisan test --filter HomeControllerTest and all the database was deleted! HOW COME?????
here is the test code:
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class HomeControllerTest extends TestCase
{
use RefreshDatabase;
public function test_home_view_requires_authentication()
{
// Log in as the created user and try to access the home page
$response = $this->postJson('/login', [
'email' => 'test#example.com',
'password' => 'password',
]);
$response->assertStatus(302);
$response->assertRedirect(route('home'));
$response = $this->get(route('home'));
$response->assertOk();
$response->assertViewIs('home');
$response->assertViewHasAll(['corretora', 'propostas']);
}
/**
* Test if home page can be accessed by a guest user.
*
* #return void
*/
public function test_home_view_requires_guest()
{
$response = $this->get(route('home'));
$response->assertStatus(302);
$response->assertRedirect(route('login'));
}
}
Why my database was deleted? i do have a backup, of course, but should test do it?
There was not an error. The use of the use RefreshDatabase; do the erasing.
I remove it and now is working good.
We have a lot of API level automated tests written as collections of requests in Postman.
We have a script to run all collections in automated manner.
Is there a way to label/run only subset of requests e.g. with some label e.g. as smoke suite, without copying requests to new collection(s) and run then explicitly (as this yields the need to maintain same tests in 2 places...)?
There might be labels, groups or some script that skips the request is env variable is set...
you can create folders and organize test like
smoke_and_regression
smoke_only etc
you can specify which folder to run using --folder arguent when using newman as command line tool
you can also control the execution flow using postman.setNextRequest .
and also you can run newman as an npm module.
you just need to write a logic to read the collection file and get all folder names containing "smoke" for eg and pass it as an array
const newman = require('newman'); // require newman in your project
// call newman.run to pass `options` object and wait for callback
newman.run({
collection: require('./sample-collection.json'),
reporters: 'cli',
folder: folders
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
});
Just update for the comments:
in old and new UI you can select which folder to execute in collection runner
Get all requests in the collection:
you can also get information about all the requests in a collection by using :
https://api.getpostman.com/collections/{{collection_UUID}}
to get uuid and api key goto :
https://app.getpostman.com
Now for generating api key >
goto account settings > api key and generate api key.
to get collection uuid goto specific workspace and collection and copy the uuid part from url:
Now in your collection
Rename all requests as:
get user details [Regression][Smoke][Somethingelse]
get account details [Regression]
Then Create a new request called initial request and keep it as the first request in your collection:
url: https://api.getpostman.com/collections/8xxxxtheuuidyoucopied
authorization: apikey-header : key: X-Api-Key and value: yourapikey
test-script :
pm.environment.unset("requestToRun")
reqeustlist = pm.response.json().collection.item.map((a) => a.name)
requestToRun = reqeustlist.filter((a) => a.includes(pm.environment.get("tag")))
let val = requestToRun.pop()
pm.environment.set("requestToRun", requestToRun)
val ? postman.setNextRequest(val) : postman.setNextRequest(null)
Now set the envirnoment variable as what you want to look for eg: run script that contains text "Regression" then set pm.environment.set("tag","Regression")
Now in your collection-pre-request add:
if (pm.info.requestName !== "initial request") {
let requestToRun = pm.environment.get("requestToRun")
let val = requestToRun.pop()
pm.environment.set("requestToRun", requestToRun)
val ? postman.setNextRequest(val) : postman.setNextRequest(null)
}
Output:
Example collection:
https://www.getpostman.com/collections/73e771fe61f7781f8598
Ran only reqeusts that has "Copy" in its name
I already found few informations like
Symfony2 access private services in tests
or
Replace Symfony service in tests for php 7.2
But I dont know why its not working.
I have an autowiring service.
class MailService {
public function __construct(\Swift_Mailer $mailer, Environment $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}
}
config/services_test.yaml
services:
# default configuration for services in *this* file
_defaults:
#autowire: true # Automatically injects dependencies in your services.
#autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: true
test.swiftmailer.transport: '#Swift_Mailer'
And when I try to replace.
$mailer = $this->getMockBuilder(\Swift_Mailer::class)
->disableOriginalConstructor()
->getMock();
$mailer->expects($this->once())->method('send')->willReturn(1);
self::$container->set('swiftmailer.mailer.default', $mailer);
self::$container->set('swiftmailer.default', $mailer);
self::$container->set('swiftmailer.mailers', [$mailer]);
But I dont know why its not working.
Any ideas? :)
I am currently working on some PowerShell script for SharePoint farm configuration (for example a script for SPWebapplication creation, User profile service application creation, MMS service application creation or search service application creation). My requirement is to test this module using Pester framework. I have very basic understanding about Pester. A sample code for web app creation is below:
$webApplicationName = "A Name"
$hostingMainURL = "http://.....local"
$ContentDatabase = "Datacom_WebApp_ContentDB"
$applicationPoolDisplayName = "TestApppool"
$applicationPoolIdentity = (Get-SPManagedAccount "DEV\Apppool accountName")
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$ap = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication
$applicationPoolDisplayName -ApplicationPoolAccount $applicationPoolIdentity -
Port 80 -AuthenticationProvider $ap -DatabaseName $ContentDatabase
Write-Host "Set content database limits settings for $ContentDatabase..." -Foreground "green"
Set-SPContentDatabase -Identity $ContentDatabase -MaxSiteCount 1 -WarningSiteCount 0
New-SPSite -Url $hostingMainURL -owneralias $username -Name $webApplicationName -Description "Hosting root site collection"
I need a starting point from here. I need some advise on how I can create some test cases on Mocking for example:
Mock New-SPWebapplication
Mock Get-SPManagedAccount
Mock New-SPSite
inModuleScope 'ModuleCallingSpWeb' {
function Get-SPWebApplication {}
Mock -ModuleName ModuleCallingSpWeb Get-SPWebApplication
}
Based on this excellent screencast and example, I've been able to unit test my Ember (RC7) app successfully, writing to model objects and such. I'm having trouble with integration testing. I even tried the most basic sort of test, as seen below, but to no avail. Any tips on what I'm doing wrong?
I'm getting this error from the console:
LOG: 'App ready'
INFO: 'generated -> route:application', Object{fullName: 'route:application'}
LOG: 'NeedsAuthMixin: user not authenticated (1).'
INFO: 'Rendering application with ', Object{fullName: 'view:application'}
INFO: 'Rendering login with ', Object{fullName: 'view:login'}
LOG: 'Transitioned into 'login''
LOG: 'testing... login screen loads OK 1'
LOG: 'Transitioned into 'login''
Chrome 28.0.1500 (Mac OS X 10.6.8) Integration Tests - load login page FAILED
Expected 1 assertions, but 0 were run
Background: As you can see, as my app loads, it checks for user authentication, whereupon it transitions to a login page if user isn't authenticated.
This is the code that calls the test (generated from coffeescript):
asyncTest("test: load login page", function() {
expect(1);
console.log("testing... login screen loads OK 1");
return visit("/login").then(function() {
return ok(1 === 1, "Value equal 1.");
});
});
My Karma config file is here.
Bryan
I think it will work if you use test() instead of asyncTest()