How to cast groovyx.net.http.HttpResponseDecorator to user defined class - groovy

I am writing a Integration Test class using Spock Framework, there my response hold inside groovyx.net.http.HttpResponseDecorator
I am trying to cast into my own class lets say TestEntity using following step
HttpResponseDecorator response = getRestClient().delete([path: "$BASE_URL"+"/96023"])
Here the Path method returns TestEntity, Now I want to get that entity and write assertions
TestEntity entity = (TestEntity)response.getData()
When I write this statement I am getting ERROR!
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object

What class is returned by getData() depends on what content type returns the REST API you are calling.
Add this line to check what class is Groovy using in your case:
println response.data.getClass()
... or use debug in your IDE to obtain the same information.
For example for content type:
application/json class org.apache.groovy.json.internal.LazyMap is used
application/xml class groovy.util.slurpersupport.NodeChild is used
text/plain class java.io.StringReader is used
If you are testing backend which uses the TestEntity class as a response (for example using #RestController and #RequestMapping in Spring) then you will not have TestEntity instance in the client (Spock test).

Related

Mocking a public method that has a private method call inside using Mockito (not Powermockito)

I am testing for methodA() in the class :
class Test{
public String methodA(String str){
...
methodB("s1","s2");
...
}
private String methodB(String s1, String s2){
...
}
}
What I have tried in my test class:
Method methodBReflect = Test.class.getDeclaredMethod("methodB", Test.class,String.class, String.class);
methodBReflect.setAccessible(true);
Test testForSpy=new Test();
Test spyTest=spy(testForSpy);
doReturn("return string").when(spyTest..)... // <-- What should be done here?
//methodBReflect.invoke(spyTest, "args1","args2");
P.S: I don't need a solution using powermock as I have some organizational constraints using it.
You shouldn't be testing that method A calls method B. You should test that method A does what method A is supposed to do - that is, it gives the correct output for whatever input you give it. Your test shouldn't care whether method A works by calling method B, or by doing all its processing inline.
Therefore, there's no need to mock or stub anything. Your tests will consist of a bunch of calls to method A, along with verification that the output is what you expect.
You only need to use Mockito (or some other mocking framework) when you're testing a class that interacts with another class entirely; not when the class under test interacts with itself.

Possibility to disable the property syntax for accessing a getter in groovy?

Let's I have a groovy class like:
class SomeClass {
String myProperty = 'foo'
}
Usually in groovy is will be totally valid to access the value using the property name or the getter - which usually gives the same result for SomeClass:
SomeClass someClass = new SomeClass()
assert someClass.myProperty == 'foo'
assert someClass.getMyProperty() == 'foo'
However - due to a flaw in the Jenkins Pipeline implementation - sometimes(!) you are forced to use the getter - as the plain property access will not work (when using some class hierarchy), see: JENKINS-47143. Bad thing is that the same code may work for some jobs while it doesn't for others:
SomeClass someClass = new SomeClass()
assert someClass.myProperty == 'foo' // sometimes throws 'property not found' error
assert someClass.getMyProperty() == 'foo'
Now I already have couple of unit tests for our Jenkins shared library - but what is missing would be a way to detect a property access, in short: A way to prohibit the property access so the unit tests will already complain in advance.
The following code:
class SomeClass {
String myProperty = 'foo'
}
SomeClass.metaClass.getProperty = { String name ->
throw new RuntimeException("tried to get property ${name}, property access only allowed via getXX() methods")
}
def s = new SomeClass()
println(s.myProperty) // a
println(s.getMyProperty()) // b
will throw an exception for line a but not throw an exception for line b. I suspect this will not be possible if SomeClass was written in java, but assuming a groovy class this could be a way to accomplish what you want.
Running the above will result in:
─➤ groovy solution.groovy
Caught: java.lang.RuntimeException: tried to get property myProperty, property access only allowed via getXX() methods
java.lang.RuntimeException: tried to get property myProperty, property access only allowed via getXX() methods
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...

Add strong typing to objects from JsonSlurper

I'm having some trouble getting typing to work with the JsonSlurper in Groovy. I'm fairly new to Groovy, and even newer to adding strong types to it - bear with me.
Right now I've created a trait which defines the general shape of my JSON object, and I'm trying to cast the results of parseText to it.
import groovy.json.JsonSlurper
trait Person {
String firstname
String lastname
}
def person = (Person)(new JsonSlurper().parseText('{"firstname": "Lando", "lastname": "Calrissian"}'))
println person.lastname
This throws
Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{firstname=Lando, lastname=Calrissian}' with class 'org.apache.groovy.json.internal.LazyMap' to class 'Person' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Person(org.apache.groovy.json.internal.LazyMap)
...
I can see why my code doesn't make sense, I'm not trying to change the type of the data (casting), I'm just trying to let my IDE know that this is what's inside of my object.
Is it possible to at least add code completion to my JSON objects? I'd love to get runtime type checking, as well, but it's not necessary.
you could try to use delegate
this allows to wrap class around map
import groovy.json.JsonSlurper
class Person {
#Delegate Map delegate
String getFirstname(){ delegate.get('firstname') }
String getLastname(){ delegate.get('lastname') }
}
def person = new Person(delegate:new JsonSlurper().parseText('{"firstname": "Lando", "lastname": "Calrissian"}'))
println person.lastname
or for example use Gson for parsing:
#Grab(group='com.google.code.gson', module='gson', version='2.8.5')
import com.google.gson.Gson
class Person {
String firstname
String lastname
}
def person = new Gson().fromJson('{"firstname": "Lando", "lastname": "Calrissian"}', Person.class)
assert person instanceof Person
println person.lastname
This actually is a cast and Groovy will try to turn your Map into said object.
From the docs:
The coercion operator (as) is a variant of casting. Coercion converts object from one type to another without them being compatible for assignment.
The way this works for a POJO is to construct a new object using the Map-c'tor. This will either unroll into calling setters or works directly with static compilation.
Be aware, that using maps with excess keys will lead to errors. So I'd only use this for toy projects. Use a proper JSON-mapper like e.g. Jackson instead.
So the solution here is to not use a trait (which is basically a interface) but a regular class.

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

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

Micronaut CompileStatic JSON object -Static type checking- No such property: bookid for class: java.lang.Object

In my Micronaut Controller I have below code to parse the JSON object. when I use #CompileStatic annotation it throwing this below error.
#Post("/save")
def save(#Body Object JSON) {
String bookid=JSON?.bookid
String name=JSON?.name
def b =bookService.save(bookid,name)
return HttpResponse.created(b)
}
Error
BookController.groovy: 58: [Static type checking] - No such property: bookid for class: java.lang.Object
Is there way to fix this error message with compilestatic annotation?
Thanks
SR
With Help of Jeff Brown I have changed. my save method like this.
#Post('/')
Book save(Book b) {
bookService.save b
}
Micronaut JSON post strip the Qutoes
You can also work with your method instead of changing it for parsing.I encountered the same problem and the method that worked for me is using String instead of object. Just use JSON String along with #BODY and then parse it using ObjectMapper().
here is the answer i posted at some other question, hope it will help you out.
https://stackoverflow.com/a/54905403/7803105

Resources