Unit Testing with groovy - groovy

New to groovy and java. Installed groovy,plugin with eclipse and created a groovy project
I am able to run groovy scripts and groovy class. But GroovyTestCase class is not getting resolved. Any help is appreciated.
package p1
import groovy.util.GroovyTestCase
class MyTest extends GroovyTestCase { //GroovyTestCase keyword is showing this error: type junit.framework.TestCase cannot be resolved. It is indirectly referred from required .class files
void testSomething() {
assert 1 == 1
assert 2 + 2 == 4 : "We're in trouble, arithmetic is broken"
}
}

GroovyTestCase is JUnit 3, If you want to use Junit4, don't extend the class, instead use the #Test annotations like in Java.

You can use JUnit as it was pointed out before, but on Groovy usually the library that it is used it is called Spock. Next question would be Why Spock, then check this out.
We have been using it for a while, and it works like a charm. Highly recommended.

Related

Invoking groovy method in Mule 4

I have built a complete groovy project with JPA repo for data persistence operations. Now I want to invoke the methods from the script in Mule 4 without changing anything in the groovy project.
eg. CustomerService.groovy (pseudo code)
import com.example.dao.CustomerDao.groovy
... other imports...
#Service
class CustomerService {
#Autowired
CustomerDao cDao
#Transactional
publid Customer createCustomer(Customer customer) {
return cDao.save(customer)
}
... other methods...
}
CustomerDao.groovy
import spring.JPA (the original import path may vary)
#Repository
class CustomerDao implements JPARepository<Customer, Integer> {
}
This project is working in Mule 3. In Mule 3 we have an Invoke component which could be used to invoke the methods from the groovy script. The Mule 4 the Invoke component is compatible only with Java and not groovy.
The Scripting module's 'Execute' component can invoke a groovy script but not sure how to invoke the method. Is the any work around for this in Mule 4?
Problems occured as of now
In 'Execute' component if I import another file I get the error as
Unalbe to resolve class com.example.dao.CustomerDao
# line 3 column 1,
import com.example.dao.CustomerDao.groovy
^
Found a solution for similar problem https://help.mulesoft.com/s/article/Compilation-exception-in-Mule4-x-when-using-Groovy-script-with-Import-statement but unable to implement it.
In the article, he developer had an issue with an apache dependency, which he/she could get from mvn repo. I am trying to import a groovy file which I have developed. So unable to add it in the dependency. I tried adding the groovy project in my local repo and fetch it but it didn't work. Moreover, when this Mule 4 application will be deployed on CloudHub it will have an issue as it won't be able to access my local repo.
Need a solution to add a spring-groovy project to Mule 4
Thanks :)
The problem is that the Groovy script executed by the Scripting Module is trying to import a class, which is not in Java's classpath. So it throws the error. The class is in another Groovy source file. What you can do is to compile the Groovy code into an actual Java class. You can try one the methods described in the Groovy documentation to integrate a Maven plugin with your Mule application pom.xml file.
Another alternative if you have a large number of Groovy classes is to create a separate project to build a Jar library, then use the solution from the KB article you mentioned.

Mocking Matcher with non native class

I am trying to write a #test in Junit using mockito and powermock. I have no issue stubbing methods that have no parameters. However when I try telling mockedBank to return true no matter what is passed into latePay, I get java.lang.NullPointerException. latePay is a final method that is why I am using powermock. Any suggestions are much appreciated.
BankGenerator mockedBank = PowerMockito.mock(BankGenerator.class);
when(mockedBank.latePay(Matchers.any(MoneyCalculator.class))).thenReturn(true);
Have you added the correct annotations to your class containing the tests?
For example:
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassWithFinalMethod.class)
public class ClassContainingUnitTests {
...
}
I have used PowerMock with EasyMock in the past, and forgetting to include these annotations sometimes resulted in strange results.
For further reference, check here:
http://www.codeproject.com/Articles/806508/Using-PowerMockito-to-Mock-Final-and-Static-Method
Hope this helps.

Access tied files through groovy in jenkins

I'm building a Jenkins plugin, and am handling the UI components using Groovy. In jelly, you can use "${it.something}" to access information in the java file tied to the jelly file, as shown here:
class:
public String getMyString() {
return "Hello Jenkins!";
}
jelly:
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout"
xmlns:t="/lib/hudson" xmlns:f="/lib/form">
${it.myString}
</j:jelly>
from https://wiki.jenkins-ci.org/display/JENKINS/Basic+guide+to+Jelly+usage+in+Jenkins.
I'd like to do the same thing in groovy, but can't seem to find an example of how it's done. Any examples?
After even more searching and some luck, I found the correct way to do this. If I was to use the class in my question but wanted to use groovy instead of jelly, the groovy code would look like this (this puts the string in the textbox):
package something.something;
import lib.JenkinsTagLib
import lib.FormTagLib
def f = namespace(lib.FormTagLib)
t=namespace(JenkinsTagLib.class)
f.entry(title:"text", field:"text") {
f.textbox(value:instance?.text)
}

Populating variables in a groovy script from a java program

I know how to call Groovy code from Java code, but can you, while running Groovy script script.groovy, ask a Java program to populate its varabies?
// script.groovy
import static org.mydomain.WiseJavaProgram.*;
pleasePopulateMeWithVariables();
println numberOfLegs // 2
// We didn't declare numberOfLegs in our sript, the Java program set it for us.
I guess maybe for that script.groovy should pass its environment to the pleasePopulateMeWithVariables method, but I haven't found how to do that. Is this even possible?
The case where I want to use such behavior: I have script.groovy, and also an undefined number of groovy scripts of which Java program knows, but of which script.groovy doesn't know, and I want to add what is declared in them to script.groovy. Basically those additional scripts are data, for example descriptions of various products and their features. This is easy if you run a Java program that creates GroovyShell and evaluates in it data-scripts and then script.groovy, but for me it is necessary that we initially call script.groovy, not the Java program.
Just as usual, while asking the question I was one step behind the answer -__-
The "environment" I was searching for is the Script object itself, available from script.groovy simply as this. So:
// script.groovy
import static org.mydomain.WiseJavaProgram.*;
populateWithVariables(this);
println numberOfLegs // 2
// WiseJavaProgram.java
public class WiseJavaProgram {
public static void populateWithVariables(Script script) {
script.evaluate('numberOfLegs = 2');
script.evaluate(new File("another.groovy"));
script.evaluate(new File("yetAnother.groovy"));
}
}

Calling groovy script from other groovy script

I want to call a groovy script from the other groovy script... anybody can help me in this ASAP..
example :
Class A having some code and it should call from B
class A{
static main(args){
println "Hello.. calling A Class"
}
}
I want to create a new class like B.groovy
class B{
static main(args){
// I need code for this to call A.groovy
}
}
Putting the following at the top of your script will load the contents of a groovy file.
evaluate(new File("/path/to/script/MyScript.groovy"))
You could also add this to the groovy classpath if you need to do something like this often. Hope this helps.
additionally if you need to run other scripts from your script you could do the following...
def script = new GroovyShell();
def args = ['Hello World'];
script.run(new File("/path/to/script/MyScript.groovy"), args as String[]);
Too late for the party (any beer for me?) but here I´ll show you 2 more flavors:
1) Remember the concept of Java´s CLASSPATH? That aplies to Groovy (because Groovy is Java!):
"The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes.”
In order to run the script B.groovy you have to inform the location of the A.groovy (A class):
groovy –cp c:\groovy\yourscripts c:\groovy\scripts\B.groovy
The command above is telling the runtime to look in the c:\groovy\yourscripts folder because there is where we have our classes and we need them to run the B.groovy script successfully.
2) Use the GroovyClassLoader to load your scripts at runtime and using the code!
Both ways solve your needs. Now the next question is when to use each?

Resources