What is the type of props in JMeter's world? - groovy

I'm writing my test cases in JMeter and I'm at the point when information should be passed between threads. The only thing I don't know is the type of props, so I can't use it easily in my Groovy code.
What is the type of props?
My groovy code looks like this:
class NiceGroovyClass {
JMeterVariables vars
Logger log
<props.type???> props
ConfigurationManager(
Logger log,
JMeterVariables vars,
<props.type???> props) {
this.vars = vars
this.log = log
this.props = props
}
}

The documentation shows that it is a java.util.Properties instance
props
(JMeterProperties - class java.util.Properties) - e.g. props.get("START.HMS"); props.put("PROP1","1234");
You could always check the result of props.getClass().toString() to validate this

In Groovy you can use the following methods to get information on an arbitrary object:
dump()
inspect()
Example output:
So props is basically an instance of java.util.Properties
Check out Top 8 JMeter Java Classes You Should Be Using with Groovy article to learn more about the most popular JMeter API shorthands available from JSR223 test elements

Related

How to create instance of WCMUsePojo in my Prosper spec?

I have a functioning WCMUsePojo Groovy class which is called from a sightly html component. I am trying to create an instance of my WCMUsePojo class for testing based on the content from the Prosper setup method.
It's basically the same type of question as How can I create an instance of WCMUsePojo in a servlet for a specific page? But I don't see it answered and this is specifically about how to unit test methods in WCMUsePojo classes within the Prosper framework. Is there a Java or Groovy equivalent to Sightly's data-sly-use attribute?
def setupSpec() {
pageBuilder.content {
page_with_new_gridwrapper {
'jcr:content'{
'gridpar' {
'my_gridwrapper'('sling:resourceType':'my/components/my_gridwrapper') {
}
}
}
}
}
}
def "Test Page with New Grid Container"(){
Page page = pageManager.getPage("/content/page_with_new_gridwrapper")
// the following 2 lines return null :-(
// but I would prefer these to return an object with the type MyGridContainerHelper
MyGridContainerHelper cmp = page.getContentResource().getChild("gridpar/my_gridwrapper").adaptTo(MyGridContainerHelper.class)
Component cmp2 = WCMUtils.getComponent(page.getContentResource().getChild("gridpar/my_gridwrapper"))
expect:
page != null //passes
page.getContentResource().getChild("gridpar/my_gridwrapper") != null //passes
cmp != null // fails
cmp2 != null // fails
cmp.resourceType == "my/components/my_gridwrapper" // fails
}
To adapt an instance of MyGridContainerHelper from a resource object, you can implement your helper class using Sling Models rather than extending WCMUsePojo. Prosper supports registration of #org.apache.sling.models.annotations.Model-annotated classes by using the following syntax in the setupSpec block of your specification:
slingContext.addModelsForPackage("helper.class.package.name")
This eliminates the need to manually construct a Bindings object and initialize the POJO; the Sling model factory does all the work for you. Since Sightly's "use" attribute supports any class that is adaptable from a Resource or SlingHttpServletRequest, no additional changes are required for your existing Sightly template.
I ended up instantiating the object and calling the init method passing in a SimpleBindings object containing the resource I was testing with. This seems to work well for my purposes.
MyGridContainerHelper gridContainer = new MyGridContainerHelper();
SimpleBindings bindings = new SimpleBindings()
bindings.put("resource", page.getContentResource().getChild("gridpar/my_gridwrapper"))
gridContainer.init(bindings)

how do I configure my testng IReporter to accept parameters

IReporter is an interface that has a single void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) method. I would like to make the behavior of the reporter configurable so I can pass options to it when run on the commandline. The documentation explains how to pass parameters to a reporter on the commandline:
-reporter The extended configuration for a custom report listener. Similar to the -listener option, except that it allows the
configuration of JavaBeans-style properties on the reporter instance.
Example: -reporter
com.test.MyReporter:methodFilter=insert,enableFiltering=true You
can have as many occurences of this option, one for each reporter that
needs to be added.
So it seems I should be able to call testng with -reporter com.my.reporter:key1=value1,key2=value2
but WHERE do I get the values passed in.
I've looked at the XMLReporter provided by testng, and it has a private final XMLReporterConfig config = new XMLReporterConfig(); line, but I can't find out how the config is ever populated.
Magic, that's how it's done :-) It appears it looks for instance variables on your class that implements IReporter with the same name. It does need a stronger type than Object or def though it seems. Here's an example.
class MyReporter implements IReporter {
int foo; //<-- populated when instantiated
#Override
void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
println "foo = ${foo}"
}
}
And then to execute it:
testng ... -reporter 'full.path.to.MyReporter:foo=42'

Extending Groovy String class

Groovy allows to do some nice things with strings in frontend pages, like:
${"hello".capitalize()}
How can I add a new custom method to the String class? Like:
${"hello".custom()}
Use the metaClass
String.metaClass.custom = { //dosomething }
See http://www.groovyexamples.org/2010/07/19/dynamically-add-properties-to-a-class/

Mock static method with no parameters in Groovy

I need to mock a static method. I'm using the EMC approach described at Mocking static methods using groovy. Like this
TestDaemon.metaClass.'static'.newDownloadManager = {downloadManager}
The method newDownloadManager has no parameters and for some reason it is not replaced. The original code is called. In debug mode I can see that the closure that I define has a parameter. May be that's the reason? How can I define a closure without parameters? Or how can I mock a static method with no parameters?
Meta class changes aren't visible to Java code. Groovy can't help you to mock a static method that gets called from Java code. You will have to use something like JMockit instead (or refactor the code under test).
A closure written like that has an implicit parameter. Write the closure with { -> } syntax. Example:
x = { println "foo" }
y = { -> println "foo" }
assert x.parameterTypes as List == [Object]
assert y.parameterTypes as List == []

Groovy: stub typed reference

I have a Groovy class similar to
class MyClass {
Foo foo
}
Under certain circumstances I don't want to initialize foo and want to stub out all the calls to it. Any methods that return a value should do nothing. I could do it like this:
Foo.metaClass.method1 = {param -> }
Foo.metaClass.method2 = { -> }
Foo.metaClass.method3 = {param1, param2 -> }
While this will work, it has a couple of problems
Tedious and long-winded, particularly if Foo has a lot of methods
This will stub out calls to any instance of Foo (not just foo)
Although Groovy provides a StubFor class, if I do this:
this.foo = new groovy.mock.interceptor.StubFor(Foo)
I get a ClassCastException at runtime. Although this would work if I could redefine foo as:
def foo
But for reasons I won't go into here, I can't do that.
Thanks,
Don
I found the solution:
this.foo = {Object[] args -> println "I don't do anything"} as Foo
You need to pass the Foo instance to your MyClass object. In the test, pass in a stub implementation. In the real program pass in a real implementation.
You don't need any special framework to write the stub. If you're only stubbing queries to Foo and are not interested in expecting commands to it, then it's easier to write a stub implementation by hand. A mock object library is overkill and will confuse later readers of the code who will expect the test to include expectations.
You could make a stub with a map as well, making it possible to stub multiple methods, like so:
def stubbedList = [empty : { false }, get: {index -> "always return this"}] as ArrayList
If you stub out a class (like in the ArrayList example above), then the methods that you do not override are kept as they are implemented in the class. You can also stub out interfaces obviously.
If you are in need of mocking capabilities (i.e verifying behaviour in a test, like counting the number of calls to a given method), I would strongly recommend checking out the Spock test framework. It has really great support for more advanced stubbing and mocking.
I'm guessing this is for test purposes only.
The line:
Foo foo
creates a getter / setter pair, so you can inject a mock in your test cases by doing this:
new MyClass().foo = new MockFoo()
If you don't want to create the mock for yourself, try a mocking library. I recommend using mockito. With this small library you can do something like this:
import static org.mockito.Mockito.*;
new MyClass().foo = mock(Foo.class);

Resources