How can we write java code in JMETER?
I got some information from google,Java Sampler is using for that and I tried that way
Just i did copy paste some codes from googe,but getting errors from import also ,Always org.apache.jmeter is showing error,Any body can tell me about implementation and sample code alao
This is my java code
package com.code4reference.jmeter.functions;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
public class JavaRequestSamplerDemo extends AbstractJavaSamplerClient {
#Override
public SampleResult runTest(JavaSamplerContext ctx) {
JMeterVariables vars = JMeterContextService.getContext().getVariables();
vars.put("demo", "demoVariableContent");
SampleResult sampleResult = new SampleResult();
sampleResult.setSuccessful(true);
sampleResult.setResponseCodeOK();
sampleResult.setResponseMessageOK();
return sampleResult;
}
}
If you're missing org.apache.jmeter.* package you need to add everything all jars from /lib/ext folder of your JMeter installation to Java build classpath. Refer to your IDE documentation on how to do it.
In Eclipse it can be done via Project -> Properties -> Java Build Path
In Idea it's in Project -> Dependencies
If you're using Apache Ant, you need to do something like
<path id="build.classpath">
<fileset dir="${path.to.your.jmeter.lib.ext.folder">
<include name="*.jar"/>
</fileset>
<path>
There are at least 3 places where you can inject your Java code.
1. Java Request.
Examples:
/src/protocol/java/org/apache/jmeter/protocol/java/test/JavaTest.java
/src/protocol/java/org/apache/jmeter/protocol/java/test/SleepTest.java
Which are source code for JavaTest and SleepTest Java Request Samplers
2. Your own Sampler
Example:
/src/examples/org/apache/jmeter/examples/sampler/ExampleSampler.java
3. Beanshell or JSR233 Sampler
JMeter supports Beanshell and JSR233 scripting, both can understand Java syntax.
JMeter source code is available from JMeter Downloads page.
Except Java Sampler which requires
knowledge with specific JMeter context, other options:
You can write Java code in JSR223 element which is capable to execute any JSR223 supported language as groovy.
The JSR223 Sampler allows JSR223 script code
Inside other JMeter elements, as If Controller, You can execute Java code inside __BeanShell function or __groovy
For performance it is better to use __groovy function
Package your code in a jar and put it in JMeter's lib folder. Then you can execute its public methods.
I would say use BeanShell for something like this unless what you are going for is to wrap some of the JMeter functionality into a Java app. It seems common for people to create test plans adding some more advanced functionality using BSF or BeanShell then running it all headlesss with Ant.
Related
Currently I'm using Spring Cloud Contract to test my publishing of events from one microservices to another. After the test run succesfully, I would publish the stubs to be use by other microservices.
In the publisher microservice, I write a Groovy test with Contract.make and specify the input and outputMessage like below.
input {
triggeredBy "triggerEventMethod()"
}
outputMessage {
sentTo "somewhere"
body """
{
"field": "sampleData"
}
"""
headers {
header("contentType", applicationJson())
header("eventName", "SampleEventName")
}
}
In my BaseClass, I annotated the class with #ImportAutoConfiguration(NoOpContractVerifierAutoConfiguration::class) to configure the MessageVerifier and declare my triggerEventMethod() to run some method which would trigger the ApplicationContext to publish the SampleEventName. I have my own custom implementation class of MessageVerifierReceiver which would listen to the SampleEventName and store the message in a ThreadLocal then my override of the receive method just try to retrieve the message available in the ThreadLocal. Then the generated test by spring-cloud-contract would just verify the content of the body and headers of the event.
As far as it goes, this test has been working for more than 2 years and currently after upgrading spring-cloud-contract from 2.2.3.RELEASE to 3.1.1, I'm experiencing errors while running the generated test.
My observation on the newly generated version of test is that it would generate a YAML version of my Groovy contract and place it relatively with the generated test class in generated-test-sources folder. When running the test, it would try to reference the .yml file and hit FileNotFoundException of the .yml file. I try manually remove the the logic where it look for the file and my test case would pass after that, but since it is a generated test, it technically should not be edited this way. Sample referencing of the .yml file as below.
ContractVerifierMessage response = contractVerifierMessaging.receive("somewhere",
contract(this, "sampleEvent.yml"));
Does anyone know any way which I could exclude the generation of .yml or referencing of the YAML contract in my generated test? Or if you have better suggestions of how I could refactor my test of ensuring applicationContext publishing works?
The Groovy files are then generated to stubs for my other microservices to do contract testing and serve as mock data.
I have a jar file where i have one java class.I add that to jmeter and call that jar in sampler.When the request is hit I face java.lang.NoSuchMethodError for one of the methods inside that java class.That method doesn't need any maven dependencies as I use default java functions inside it.I tried manually including that jar to jmeter lib folder but no luck.
From my Java Maven framework,I have a baseclass where i have all my reusable functions.I convert this class into a jar file and load it in jmeter. I also convert my whole java project into a runnable jar file and load in jmeter.Now in one of my sampler,I have my JSR233 Postprocessor.i write groovy script and call the method inside that jar where my whole java project is bundled.So when i run that sampler my http request is hit and after that my jar will execute.
Now everything looks good.But when the code reaches the line where i call my reusable function from my baseclass,i get Nosuchmethod error. The java jar file is running properly in CMD and jenkins and also my java code is properly running in eclipse
Your question is missing essential information like:
How does the function and the fully qualified class name look like
How exactly do you package the .jar
How do you call it from the JSR223 Sampler
If you have a runnable .jar and wait to invoke its "main" function programmatically from JMeter's JSR223 Test elements you will need to do something like:
new Thread(new Runnable() {
public void run() {
your.class.main('arguments here')
}
}).start();
Demo:
If anything goes wrong in the majority of cases the reason or at least a clue can be found in jmeter.log file
More information on the concept of running functions from .jar files in JSR223 Test Elements - How to Reuse Your JMeter Code with JAR Files and Save Time
As can be seen from the top of documentation of class org.gradle.api.tasks.testing.Test, test tasks can be configured using the following piece of code:
test {
// configuration here. For example:
useJUnitPlatform()
}
From usage of method useJUnitPlatform we can assume that method test is called with a Closure which has an instance of aforementioned class Test as delegate.
In Gradle, there are other similar methods which take a Closure. For example, afterEvaluate. Documentation of method afterEvaluate is readily available in documentation of class Project. This is also mentioned in the user guide:
This example uses method Project.afterEvaluate() to add a closure which is executed after the project is evaluated.
Where is the documentation of method test? I could not find it. Or maybe this isn't a method in a class, but inserted via reflection into class Project at runtime or some similar DSL magic?
test in this context is not a method per se, but rather a task named test. To figure out what exactly is going on here requires diving into the internals of Gradle itself which is not part of any public documentation because well, it's not part of the public API.
The only way to figure exactly out what is going on is to debug Gradle during its execution. The easiest way to do that is to generate a plugin project via gradle init. Write a simple Gradle build file such as (build.gradle; I am assuming you are using the Groovy DSL):
plugins {
id("java")
}
test {
useJUnitPlatform()
}
Then write a basic functional test and start debugging. I was curious myself what is going and did just that.
In the following screenshot, you can see the stack trace in the bottom left corner. As you can see, there is a lot of methods called.
There is a mixture of Groovy specific methods and Gradle specific methods. Digging further in, you will come to:
You can see here bottom right that the list of objects is:
Project (root project)
Extra properties
Extensions
Tasks
This aligns with what I mentioned earlier: Gradle will go out of its way to match to what is being asked for. This is also explained in the "A Groovy Build Script Primer" in official documentation (starting from "If the name is unqualified [...]").
Eventually, you will land in some of the public API methods:
getByName is part of NamedDomainObjectContainer which is documented. However, what actually implements that interface is not as you can see from the Javadoc here. The implementation, from debugging, is DefaultTaskContainer.
The rest I will leave to you as an exercise. Hopefully this gives you an idea as to what is going on behind the scenes.
Indeed, test { ... } in this case is not calling a method with name test. This block is a feature of the Gradle API called "Groovy dynamic task configuration block". Per Gradle documentation version 6.1:
// Configure task using Groovy dynamic task configuration block
myCopy {
from 'resources'
into 'target'
}
myCopy.include('**/*.txt', '**/*.xml', '**/*.properties')
This works for any task. Task access is just a shortcut for the tasks.named() (Kotlin) or tasks.getByName() (Groovy) method. It is important to note that blocks used here are for configuring the task and are not evaluated when the task executes.
As such, per this shortcut convention, test { ... } block is used for configuring a task registered in the project – task with name test in this case.
Although nowadays I'd recommend using Gradle's Configuration Avoidance API to configure a task lazily instead of eagerly:
project.tasks.named('test', Test).configure {
it.useJunitPlatform()
}
See getByName replacement in the table "Existing vs New API overview".
Using IntelliJ and a xml soap response, I get a xpath generated that is unique using IntelliJs built in functionality.
Putting this into gatling scala script
val scn = scenario("RuleEngineSimulation")
.exec(http("request_0")
.post("/EngasjementBasisA2A")
.headers(headers_0)
.body(RawFileBody("RuleEngineSimulation_request.xml"))
.basicAuth("test234","test234")
.check(xpath("/SOAP-ENV:Envelope/SOAP-ENV:Body/e:HentRisikoOversiktResponse/ef:engasjementOversiktRisikoer/ef:risikogrupper/ef:risikogruppe/ef:risikoer/ef:risiko/ef:partref/text()").saveAs("partref")))
Running this gives me the following:
Namespace prefix 'SOAP-ENV' has not been declared
Please advice.
Thanks
Magnus
I have a test class to which i have added a constructor containing a
method setCaptureScreenShotOnFailure(true)
There is an assert statement which gets failed in this test
But even though there is no screenshot being captured ( i checked the
selenium server directory)
Can anyone explain how to work with this method in
I understand i cannot use this in my setup method and i can only use
in the individual test classes
Is it correct?
Yes this is only for individual class. However, if you want more effective use then you can implement testng then create a screenshot class which extends to testlistener. So that you can capture screenshot during pass or faliure of tests. refer Selenium Testng Screenshot Listener