Getting "Too few invocations" on unit test with spock - spock

For simplicity let's take a very simple class:
public class TestingClass {
public void method1(){
System.out.println("Running method 1");
method2();
}
public void method2(){
System.out.println("Running method 2");
}
}
Now I'm writing a simple test, which checking that when we invoke method1(), method2() is invoked:
class TestingClassSpec extends Specification {
void "method2() is invoked by method1()"() {
given:
def tesingClass = new TestingClass()
when:
tesingClass.method1()
then:
1 * tesingClass.method2()
}
}
by executing this test, I'm getting the following error:
Running method 1 Running method 2
Too few invocations for:
1 * tesingClass.method2() (0 invocations)
Why I'm getting this error? Printed log is show that method2() was invoked.

You need to use Spy when testing interactions on real objects, see below:
#Grab('org.spockframework:spock-core:0.7-groovy-2.0')
#Grab('cglib:cglib-nodep:3.1')
import spock.lang.*
class TestingClassSpec extends Specification {
void "method2() is invoked by method1()"() {
given:
TestingClass tesingClass = Spy()
when:
tesingClass.method1()
then:
1 * tesingClass.method2()
}
}
public class TestingClass {
public void method1(){
System.out.println("Running method 1");
method2();
}
public void method2(){
System.out.println("Running method 2");
}
}

Related

Dart pass this as a parameter in a constructor

Lets say that I have an abstract class
abstract class OnClickHandler {
void doA();
void doB();
}
I have a class
class MyClass {
OnClickHandler onClickHandler;
MyClass({
this.onClickHandler
})
void someFunction() {
onClickHandler.doA();
}
}
And I have a class
class Main implements onClickHandler {
// This throws me an error
MyClass _myClass = MyClass(onClickHandler = this); // <- Invalid reference to 'this' expression
#override
void doA() {}
#override
void doB() {}
}
How can I say that use the same implementations that the Main class has? or is there an easier/better way to do this?
Your problem is that this does not yet exists since the object are still being created. The construction of Dart objects is done in two phases which can be difficult to understand.
If you change you program to the following it will work:
abstract class OnClickHandler {
void doA();
void doB();
}
class MyClass {
OnClickHandler onClickHandler;
MyClass({this.onClickHandler});
void someFunction() {
onClickHandler.doA();
}
}
class Main implements OnClickHandler {
MyClass _myClass;
Main() {
_myClass = MyClass(onClickHandler: this);
}
#override
void doA() {}
#override
void doB() {}
}
The reason is that code running inside { } in the constructor are executed after the object itself has been created but before the object has been returned from the constructor.

How to make override abstract method in dart or flutter

My background is from java, so i can implement abstract classes and methods in java like given bellow:
Class 1
public class Base {
public void method( VerificationCallbacks verificationCallbacks){
verificationCallbacks.signInWithEmail();
};
}
Abstract class
public abstract class VerificationCallbacks {
public abstract void signInWithEmail();
public abstract void signUpInWithEmail();
}
so we can implement these classes like
Base base = new Base();
base.method(new VerificationCallbacks() {
#Override
public void signInWithEmail() {
}
#Override
public void signUpInWithEmail() {
}
});
But now i want to implement this technique in dart or flutter
Base base = new Base();
base.method(new VerificationCallbacks());
but when i write this code to implement override methods, it shows abstract classes cannot be instantiated dart, please anyone can help me to achieve this.
class Base {
void method({
VoidCallback signInWithEmailCallback,
VoidCallback signUpWithEmailCallback,
}) {
if (true) {
signInWithEmailCallback();
} else {
signUpWithEmailCallback();
}
}
}
and
Base base = Base();
base.method(signInWithEmailCallback: () {
//
}, signUpWithEmailCallback: () {
//
});
also you can define you own alias for callback like this
typedef VerificationCallback = void Function();
and use it
class Base {
void method({
VerificationCallback signInWithEmailCallback,
VerificationCallback signUpWithEmailCallback,
}) {
// logic here
}
}

Unable to override LoginController's authFail()

I need to customize message so I tried to modify the LoginController by simply overriding the grails .plugin.springsecurity.LoginController
I have thrown AccountNotApprovedException from my customizedAuthenticationProvider.
Can someone suggest me what I am missing?
class AccountNotApprovedException extends AuthenticationException{
public AccountNotApprovedException(String message, Throwable t) {
super(message, t)
}
public AccountNotApprovedException(String message) {
super(message)
}
/** #deprecated */
#Deprecated
public AccountNotApprovedException(String message, Object extraInformation) {
super(message, extraInformation)
}
}
I override the loginController:-
class LoginController extends grails.plugin.springsecurity.LoginController {
def authenticationTrustResolver
/**
* Dependency injection for the springSecurityService.
*/
def springSecurityService
def authfail() {
//my customized code
}
}
And when springSecurity runs then it didn't call my overridden authFail()

Spock fails when PostConstruct calls a injected service

Can any one tell me how to solve the issue of PostConstruct get called before mocking:
Service:
class MyService {
SecondService secondService // injected
#PostConstruct
void init() {
myFunction()
}
void myFunction() {
secondService.doSomething()
}
}
Test:
#TestFor(MyService)
class MyServiceSpec extends Specification {
void "testing my service"() {
given:
MyService service = GroovySpy(MyService) {
myFunction() >> null
}
then:
true
}
}
Gives following error:
Invocation of init method failed; nested exception is java.lang.NullPointerException: Cannot invoke method doSomething() on null object
If you have #TestFor(MyService) - MyService instance will be created automatically and you can use it as 'service'. And you don't need to create MyService manually.
So you can only delete #TestFor(MyService) or use it and remove MyService service.
But you also need to correctly mock 'secondService'
#FreshRuntime
#TestFor(MyService)
class MyServiceSpec extends Specification {
def secondService = GroovyMock(SecondService)
def doWithSpring = {
secondService(InstanceFactoryBean, secondService, SecondService)
}
void "testing my service"() {
when:
service.myFunction()
then:
1 * secondService.doSomething()
}
}

Is it possible to log spock feature method names and clause labels?

I'd like to be able to log the spock feature names and clause labels when running some automated tests. This would help with debugging test issues when using a headless browser for automation, specifically phantomjs. Reason being, phantomjs does not always behave the same way as when using the chrome WebDriver. It would also be nice to have if this is even possible.
def "Login logout test"(){
given: "Go to login page"
...
when: "Submit username and password"
...
then: "Dashboard page displayed"
...
when: "logout"
...
then: "Returned to login page"
...
}
For example, It would be cool if I could get the above sample spock feature method to log the labels like this.
Login logout test
Go to login page
Submit username and password
logout
Returned to login page
Step1: Create a Your own spock extension Class
package com.example.spock.exetension;
public class MySpockExtension implements IGlobalExtension {
#Override
public void start() {
}
#Override
public void visitSpec(SpecInfo spec) {
spec.addListener(new MyCustomSpockRunListener());
}
#Override
public void stop() {
}
}
Step2: Create a RunListener that can listen to a spock run
package com.example.spock.exetension;
public class MyCustomSpockRunListener extends AbstractRunListener {
private boolean specFailed;
private boolean featureFailed;
#Override
public void beforeSpec(SpecInfo spec) {
// TODO Auto-generated method stub
specFailed = false;
}
#Override
public void beforeFeature(FeatureInfo feature) {
// TODO Auto-generated method stub
featureFailed = false;
}
#Override
public void beforeIteration(IterationInfo iteration) {
}
#Override
public void afterIteration(IterationInfo iteration) {
}
#Override
public void afterFeature(FeatureInfo feature) {
// TODO Auto-generated method stub
for ( BlockInfo block : feature.getBlocks() ) {
System.out.println(block.getKind().name() + " : " + block.getTexts() );
}
}
#Override
public void afterSpec(SpecInfo spec) {
// TODO Auto-generated method stub
System.out.println(spec.getName() + " : STATUS : " + specFailed != null ? "failure":"success");
}
#Override
public void error(ErrorInfo error) {
specFailed = true;
FeatureInfo feature = error.getMethod().getFeature();
if (feature != null) {
featureFailed = true;
System.out.println(error.getMethod().getName() + " : " + error.getException());
}else {
}
}
#Override
public void specSkipped(SpecInfo spec) {
}
#Override
public void featureSkipped(FeatureInfo feature) {
}
}
Step3: Register your new Spock extension
In your classpath or resource path create a below folder structure META-INF/services/org.spockframework.runtime.extension.IGlobalExtension
Have this as the content of file com.example.spock.exetension.MySpockExtension
Step4: Run your spock test and you should see output something like this.
given: "Go to login page"
when: "Submit username and password"
then: "Dashboard page displayed"
when: "logout"
then: "Returned to login page"
Login logout test : STATUS : success
You can get the name of every feature method by following :
import spock.lang.Specification
import org.junit.Rule
import org.junit.rules.TestName
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class MySpec extends Specification{
private static Logger logger = LoggerFactory.getLogger(ClassName.class)
#Rule TestName testName = new TestName()
void setup(){
def featureMethodName = testName.methodName
logger.info("feature method : " + featureMethodName)
}
}
PiggyBacking on #Raghu Kirans answer, I had to do a little bit more to get this to run the way that I wanted with Data Driven tests. In the BeforeIteration method of your RunListener I did the following:
#Override
public void beforeIteration(IterationInfo iteration) {
Optional.of(iteration)
.map(feature -> iteration.getFeature())
.map(FeatureInfo::getBlocks)
.ifPresent( blocks -> blocks.forEach(
blockInfo -> log.info(blockInfo.getKind().name() + " : " + blockInfo.getTexts())));
}
This simply prints out everything prior to each iteration. Also note that getKind().name() on the BlockInfo object does not print out the given, when, then of the spock block in our test but instead prints out SETUP, WHEN, THEN and WHERE instead. getTexts() will print out the combined texts of the block.
Example:
given: "I wake up"
and: "I drink a cup of coffee"
Will be displayed as
SETUP : ["I wake up", "I drink a cup of coffee"]
After continuously searching I found this solution for getting the test name. But can't seem to find anything on the 'when' and 'then' labels. This is okay for now.
import org.junit.Rule
import org.junit.rules.TestName
class MySpec extends Specification {
#Rule TestName name = new TestName()
def "some test"() {
expect: name.methodName == "some test"
}
}
You might want to have a look at the Spock Reports Extension

Resources