Junit set local variable - java

I'm using additional jar file in my spring boot project. The problem is that one of the methods I want to test is using method from that jar that returns a value, but also sets a value to variable that is posted to it.
String valueThatWillBeReturned;
int returnMessage = method(valueThatWillBeReturned);
I don't know why the method is write by that. I'm not the writer of that jar and I cant debug it, but it works like that. It will return int that will be stored in int returnMessage, and also will set valueThatWillBeReturned that is posted to it.
It's a problem for me to test it. I'm setting the value of int returnMessage by:
when(external.method(valueThatWillBeReturned).thenReturn(1);
But how should I set value of String valueThatWillBeReturned?
The main problem is that my code depends on String valueThatWillBeReturned that should be returned.
After Edit
I made the upper example more simpler, but will give you additional details. I'm using an external library ImageSDK.jar. It uses .dll or .so file depending on the operation system.
So by documentation I should have int[] pnMatchTemplate2Index = new int[1]; to post to the method below.
int result = libSDK.UFM_Identify(hMatcherContainer[0],
templateForIdentification,
sizeOfTemplateForIdentification,
templatesFromDBForIdentification,
sizeOfEachTemplateFromDB,
numberOfTemplatesForCompare,
5000,
pnMatchTemplate2Index);
What method returns is int result that stores the return status, but the method also sets pnMatchTemplate2Index where index of matched template is stored. After that I'm using templates.get(pnMatchTemplate2Index[0]) to get information I need.
So in the end my method depends on that parameter to return value, and I dont know how to set it by Junit to test my method return.

I found a solution to my problem. I changed the location of the pnMatchTemplate2Index variable from method to class variable.
Service.class
// Receives the index of matched template in the template array;
private int[] pnMatchTemplate2Index = new int[1];
Then in the test method I mocked it like oliver_t suggested.
ServiceTest.class
int [] mockResults = {0};
ReflectionTestUtils.setField(underTest,"pnMatchTemplate2Index", mockResults);
Where:
underTest is the class we are testing
"pnMatcherTemplate2Index" is the private variable we want to mock in the class we are testing
mockResults is the value we want to set for the private variable
That way I managed to use pnMatchTemplate2Index to get the index I want from my other method.

Related

In Jenkins pipeline how can I get the return from method to use in next stage?

node() {
stage("health check function"){
def (healthcheck) = withCredentials([string(credentialsId: 'HTTP_TOKEN', variable: 'HTTP_TOKEN')]){
def health_check = sh returnStdout:true, script:"""
#some of the script content will go here before calling the curl
health_check_code=\$(curl http://$URL)
"""
return "${health_check_code}"
}
}
stage("funcreturn"){
def status = healthcheck()
}
}
I want to get the status code from health check function stage using the healthcheck method so I can call this method in further stage of pipeline to get the current status code . But in Jenkins I am getting following error java.lang.StringIndexOutOfBoundsException: String index out of range: 1.
Is it possible to get the value from method here ?
The main problem of the code is that stages have their own scope (because { ... } is a closure). That's why healthcheck can't be found in the later stage because it is basically a local variable in a function.
One way to work around this is to make it a global variable by omitting the def in the declaration:
withCredentials(){
// some commands
healthcheck = healthcheck_code // no def used to declare variable
// this is a global variable
}
The other solution would be to (which is an lesser known fact) return from the first stage.
If you return a value from a stage, it can be assigned to a variable (at least in scripted pipelines, I don't know about declarative). If there is no explicit return the last expression will be returned. It should be possible to return from the withCredentials step as well (haven't tried it for myself yet)
def healthcheck = stage("health check function"){
withCredentials([string(credentialsId: 'HTTP_TOKEN', variable: 'HTTP_TOKEN')]){
def health_check = sh returnStdout:true, script:"""
#some of the script content will go here before calling the curl
health_check_code=\$(curl http://$URL)
"""
return "${health_check_code}"
}
}
// use healthcheck here
I am not sure how your healthcheck variable should be callable. Is that a groovy feature I am not aware of? My guess is that if (for whatever reason) you want to make it a function returning the value instead of the value itself, you need to enclose it in {} making it a anonymous function.
I cannot figure out, why you are getting the string out of range error, but I am pretty sure it happens outside of your code snippet.

Trouble splitting an array in #PostConstruct Method of my Kafka SpringBoot Application

I'm creating a Kafka Springboot listener that tracks the state of an object. I have the kafka portion working and am able to listen to the topics. I am using a Tree map to map a string key that is the topic to an object. The topic name actually contains some information that I want to use to initialize the object. My question is this ( I apologize, I'm not very familiar with SpringBoot).
In my Post Construct method, I have a string array that is coming in called locoTopics. I've verified that strings are coming in and they are of the form "ignore.ignore.mark.id". The issue I'm running into is that when I try to split the string in the Post Construct method it appears to return null even though the string definitely contains the "." expression. I say it appears, because the program appears to jump forward and skip several lines of code. To be precise, when I debug. It appears to go from the "String [] locoArray = locoTopics[i].split("\.");" line to my Object constructor immediately and skip all the steps in between. Then it appears to jump in and out of the loop. I'm very confused why this is. Is this something related to SpringBoot that is happening or am I missing something in my code? Any help would be greatly appreciated.
public class InitTrackerReceiver {
// instance variables
Map mapr = new TreeMap<String, Locomotive>();
String[] locoTopics;
public List<String> m_failureCodes;
// Moved Functionality to get loco ids into separate class, Locomotive IDs now
// gets locoids
#Autowired
public LocomotiveIDs locomotiveIDs;
//This is where loco objects will be instantiated
#PostConstruct
public void initializeLocomotives() {
// grab loco topic strings and separate into a string array
locoTopics = locomotiveIDs.getLocoString();
// Go through the loco topics from application.properties and create a Loco
// object with that string as identifier
for (int i = 0; i < locoTopics.length; i++) {
String [] locoArray = locoTopics[i].split("\\.");
String markString = locoArray[2];
String scacString = "name";
String idString = locoArray[3];
mapr.put(locoTopics[i], new Locomotive(locoTopics[i], markString, scacString, idString));
}
}
#Value("#{'${failure.init.messagefields}'.split(',')}")
List<String> typesToFail;
I figured I'd go ahead and follow up with the answer. I have no clue how this happened, but the code that was in Eclipse that was in the debugger was not the same code that was running. I don't know if this was a bug in EGIT or Eclipse. It became apparent when I ran a Maven clean and my project would no longer launch. Whenever I tried to debug, it would launch and say that it couldn't find the main class, which was my Spring application launch class. I did a Maven Build and that seemed to get everything in sync. Then the code started working as expected.

Is there a way to set a test variable in Java using Robot Framework?

I am trying to call the BuiltIN keyword 'Set Test Variable' in java. The reason being is that I want to declare some variables that are read in from the test data.
I have searched and tried many times without success. I have something like:
Selenium2Library selenium2Library = Selenium2Library.getLibraryInstances();
String[] test = new String[1];
test[0] = "hello";
selenium2Library.runKeyword("Log", test);
This gives a null pointer exception error. I get the same error when instead of Log I use Set Test Variable, which is what I want. Any help is much appreciated.

UFT/QTP: Count child objects in Java Internal Frame

I need to compare a string with all values of my text fields that are inside in a Java Internal Frame.
I already tried to use this code:
Dim getElement
Set getElement = Description.Create
getElement("class description").value = "text box"
'I tried different class names: "OracleTextField", "JavaEdit"
'getElement("micclass").value = "OracleTextField"
'getElement("micclass").value = "JavaEdit"
Set obj = Browser("xxxx").JavaApplet("Main").JavaInternalFrame("yyyy").ChildObjects(getElement)
total = obj.Count
' For loop goes here
total returns 0 all the time.
Can you tell me what I'm doing wrong?
If you need something more let me know.
I tried the following line and it works. Now i have total number of text fields available in Java internal frame.
getElement("to_class").value = "JavaEdit"
Following QTP documentation didn't help, but if you check your object properties inside your Object Repository you'll find all properties of each object. Instead of "micclass" try to use your property name. Mine was "to_class" with value "JavaEdit".
QTP Documentation explains why we should use "micclass" and differences between "micclass" and "Class Name". However none of them worked for me. I used "to_class" property and it works fine!
I'm working with UFT v12.02

How to add parameters to test cases in Test Plan using Java?

I've tried various things and googled multiple hours but couldn't find a solution to my problem.
I'm using the Quality Center OTA API via Com4j to let my programm communicate with QC.
It works pretty good, but now I've stumbed upon this problem:
I want to add new parameters to a test case in "Test Plan" using my programm.
If I used VB it would work somehow like this:
Dim supportParamTest As ISupportTestParameters
Set supportParamTest = TDConnection.TestFactory.Item(5)
Set testParamsFactory = supportParamTest.TestParameterFactory
Set parameter = testParamsFactory.AddItem(Null)
parameter.Name = name
parameter.Description = desc
parameter.Post
Set AddTestParameter = parameter
The important part is the call of AddItem() on the TestParameterFactory. It adds and returns a parameter that you then can give a name and description. In VB the AddItem-method is given Null as argument.
Using Java looks similar at first:
First I establish the connection and get the TestFactory (and the list of test cases).
QcConnect qc = new QcConnect(server, login, password, domain, project);
ITDConnection qcConnection = qc.getConnection();
ITestFactory qcTestFactory = qcConnection.testFactory().queryInterface(ITestFactory.class);
IList qcTestList = qcTestFactory.newList("");
qcTestList contains all tests from Test Plan.
ITest test = qcTestList.item(1);
ISupportTestParameters testParam = test.queryInterface(ISupportTestParameters.class);
ITestParameterFactory paramFac = testParam.testParameterFactory().queryInterface(ITestParameterFactory.class);
No problem so far. All the "casts" are successful.
Now I want to call the addItem-method on the TestParameterFactory, just like in VB.
Com4jObject com = paramFac.addItem(null);
This doesn't work. The addItem()-method always returns null. I've tried various arguments like a random String, a random Integer, the test case's ID, etc. Nothing works.
How do I use this method correctly in Java?
Or in general: How do I add parameters to existing test cases in Test Plan using Java?
Quick note: Adding test cases to Test Plan works very similar to adding parameters to this test cases. You also use a factory and a addItem-method. In VB you give null as parameter, but in Java you use a String (that's interpreted as the name of the test). But as I said, that does not work in here.
I have finally found the answer to this:
Com4jObject obj = iTestParameterFactory.addItem(new Variant(Variant.Type.VT_NULL));
iTestParameter = obj.queryInterface(ITestParameter.class);
iTestParameter.name("AAB");
iTestParameter.defaultValue("BBB");
iTestParameter.description("CCC");
iTestParameter.post();
Regards.
What you want to pass to AddItem is DBNull and not null.
In VB it's the same, but in Java & .NET it's not.
Not sure how DBNull is exposed using Com4J.
Read more about this at this site.
//C# code snippet -> You have to use DBNull.Value instead of null
//Add new parameter and assign values
TestParameter newParam =(TestParameter)tParamFactory.AddItem(DBNull.Value);
newParam.Name = "ParamNew";
newParam.DefaultValue = "DefaultValue";
newParam.Description = "AnyDesc";
newParam.Post();

Categories

Resources