Unit tests for database queries - java

How to write test cases for the class below. It checks for values of the given query in a database.
public class DboQueryCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Start DboDaoService");
DboDaoService dboDaoServcice = new DboDaoService();
dboDaoServcice.build();
String query = " select o.org_name, l.organization_id from " +
" code_value cv,code_value cv_loc,code_value_outbound cvo,location l,organization o" +
" where " +
" (cv.cdf_meaning = 'INGENI' or cv.cdf_meaning = 'MEDNEC')" +
" and cvo.contributor_source_cd = cv.code_value" +
" and cvo.alias_type_meaning = 'FACILITY'" +
" and l.location_cd = cvo.code_value" +
" and cv_loc.code_value = l.location_cd" +
" and cv_loc.code_set = 220" +
" and o.organization_id = l.organization_id" +
" order by o.org_name, cv_loc.display, cv.cdf_meaning";
System.out.println();
dboDaoServcice.report(query);
}
}

You don't. In your example, you are testing more than just a unit. Therefor, by definition, you cannot 'unit' test this. If you want to test this, at least consider using DBUnit or an in memory database like H2/HSQLDB database.
Alternatively, you could test the generated SQL commands, but I wonder what the value of that would be.

Related

How to set Multiple Option of Payment In PayUMoney Payment Gateway in Android

my dependency file here
implementation 'com.payumoney.sdkui:plug-n-play:1.6.1'
payUmoney code
private fun startPay() {
builder.setAmount(amount) // Payment amount
.setTxnId(txnid) // Transaction ID
.setPhone(phone) // User Phone number
.setProductName(prodname) // Product Name or description
.setFirstName(firstname) // User First name
.setEmail(email) // User Email ID
.setsUrl("https://www.payumoney.com/mobileapp/payumoney/success.php") // Success URL (surl)
.setfUrl("https://www.payumoney.com/mobileapp/payumoney/failure.php") //Failure URL (furl)
.setUdf1("")
.setUdf2("")
.setUdf3("")
.setUdf4("")
.setUdf5("")
.setUdf6("")
.setUdf7("")
.setUdf8("")
.setUdf9("")
.setUdf10("")
.setIsDebug(true) // Integration environment - true (Debug)/ false(Production)
.setKey(pro_merchantkey) // Merchant key
.setMerchantId(pro_merchantId);
try {
paymentParam = builder.build()
getHashkey()
} catch (e: Exception) {
Log.d("afkafbakabkab", " errors $e")
}
}
payment flow stating from here
private fun getHashkey() {
paymentParam!!.setMerchantHash(CreateHash())
PayUmoneyFlowManager.startPayUMoneyFlow(paymentParam, this as PaymentGateways, R.style.AppTheme_default, true);
}
generating hash key from this code
private fun CreateHash(): String {
var hashSequence: String = pro_merchantkey + "|" + txnid + "|" + amount + "|" + prodname + "|" + firstname + "|" + email + "|" +
udf1 + "|" + udf2 + "|" + udf3 + "|" + udf4 + "|" + udf5 +"||||||"+ pro_salt;
val hash = hashcal("SHA-512", hashSequence)
return hash
}
note :- i am getting only one payment option i want to get multiple payment options like netbanking ,Upi
you have set setIsDebug() true; for some resaons PayU have only provided test cards for testing purposes.
So, the release build will have all the options.
in simple words set setIsDebug(false) and you will get all the options.

disassemble object in array

I have a search method in the database that brings me the following result:
As you see that inside the Object [4] comes another array containing People, Pessoas, and PessoasEnderecos and more objects that have relantionship with Pessoas.
I would like it to return only this way and not inside another array as it is happening now, it should look like this:
elementData=Object[10](id=144)
[0]=Pessoas(id=166)
[1]=PessoasEnderecos(id=167)
...
i have this method:
#RequestMapping(method = RequestMethod.GET, value = "/pessoas")
public ResponseEntity<Collection<Pessoas>> buscarPessoas(HttpServletRequest request) throws Exception {
String idEntidadeCrypt = request.getHeader("DataBase");
Long idEntidade = Long.parseLong(Crypto.decode(idEntidadeCrypt));
Collection<Pessoas> pessoasBuscados = pessoasService.buscarFiltro(idEntidade);
return new ResponseEntity<>(pessoasBuscados, HttpStatus.OK);
}
and :
#Repository
public interface PessoasRepository extends JpaRepository<Pessoas, Integer> {
#Query( value="select pes, pEnd, pFis, pJur "
+ "from "
+ "Pessoas pes, "
+ "PessoasEnderecos pEnd,"
+ "PessoasFisicas pFis,"
+ "PessoasJuridicas pJur"
+ " where "
+ "pes.entidade.idEntidade = pEnd.entidade.idEntidade "
+ "and pes.idPessoa = pEnd.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pFis.entidade.idEntidade "
+ "and pes.idPessoa = pFis.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pJur.entidade.idEntidade "
+ "and pes.idPessoa = pJur.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = :parametroId " )
public Collection<Pessoas> encontrar(#Param("parametroId") Long usuarioEntidade);
how can i solve that ?
ArrayList<> does not work with magic, it has an actual implementation. elementData is the array where it stores its elements. As you can see (that is a link in the previous sentence), it is a private member of the class, so you do not interact with it, but you see it in a debugger because it exists.
If you want to return an array instead of a List, you can always use toArray() which all Lists implement.

How to grab data from a class without making it static per say [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So for example I have this class that outputs my detailed flight output that is in the java doc "Flight.java" :
public String toDetailedString() {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
and I have an Itinerary class "Itinerary.java" and I want to pull the info from Flight.java without making toDetailedString static, is that possible?
For added info, each of the variables you see "source, number, destination" are all private variables in Flight.java which I know are enclosed encapsulation. Any help is greatly valuable.
Example implementation in Itinerary.java
public String toString() {
return "The total cost is" + getTotalCost() + Flight.toDetailedString();
}
UPDATE:
In my Flight constructor I have:
public Flight(Plane plane, String number, double cost, Time departure, int duration, Airport source, Airport destination) {
this.plane = plane;
this.number = number;
this.cost = cost;
this.departure = departure;
this.duration = duration;
this.source = source;
this.destination = destination;
}
In which I created the object "f1" in my ItineraryTest class:
Flight f1 = new Flight(new Plane(Airline.American, "Airbus A321"),
"495",
79,
new Time(7, 10), 100,
Airport.PHX, Airport.LAX);
Thus I linked my object to the toDetailedString() the object "f1" was renamed to "first" in my Itinerary.java and a second object was created called "f2" and moved to "second" (to avoid confusion) :
public String toString() {
return "The total cost: "
+ getTotalCost()
+ " "
+ first.toDetailedString()
+ second.toDetailedString();
}
I thought I answered my own question, but now receive an error of:
Exception in thread "main" java.lang.NullPointerException at
Itinerary.toString(Itinerary.java:117) at
java.lang.String.valueOf(String.java:2994) at
java.io.PrintStream.println(PrintStream.java:821) at
ItineraryTest.main(ItineraryTest.java:20)
Possible, clean option is creating another class named FlightToDetailedString, with (possibly static) method toDetailedString. That method would accept instance of Flight as parameter
class FlightToDetailedString {
public String toDetailedString(Flight flight) {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
}
In my example method is not static. With non-static member mehod, FlightToDetailedString could have (and use in toDetailedString) fields of FlightToDetailedString class. For example, Airport could be member variable of FlightToDetailedString. Are you sure you want to limit yourself to one airport?
Why you do not like toDetailedString as non-static member of Flight class in first place? In example you give it is most natural solution. if your Itinerary needs to access details of Flight class, just pass instance of Flight object as argument!
The consumer of toDetailedString() doesn't need access to anything inside Flight.
Your NullPointerException is likely caused by one of the fields in the Flight instance being null.
Finally, consider using a StringBuilder instead of concatenating strings.

Unable to Select option from dropdown using JavascrtptExecutor

Can anyone provide me a failsafe(ish) method for selecting text from dropdowns on this page I am practicing on?
https://www.club18-30.com/club18-30
Specifically, the 'from' and 'to' airport dropdowns. I am using the following code:
public void selectWhereFrom(String query, String whereFromSelect) throws InterruptedException {
WebElement dropDownContainer = driver.findElement(By.xpath(departureAirportLocator));
dropDownContainer.click();
selectOption(query,whereFromSelect);
}
public void selectOption(String query, String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector(' " + query + "');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
This seems to successfully populate the box with text but when I hit 'Search' I then receive a message saying I need to select an option, suggesting it has not registered the selection?
I would rather avoid JavaScriptExecutor but haven't been able to make these Selects work with a regular Selenium Select mechanism
I would set up a function for each dropdown, one for setting the departure airport and another for setting the destination airport. I've tested the code below and it works.
The functions
public static void setDepartureAirport(String airport)
{
driver.findElement(By.cssSelector("div.departureAirport div.departurePoint")).click();
String xpath = "//div[contains(#class, 'departurePoint')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
public static void setDestinationAirport(String airport)
{
driver.findElement(By.cssSelector("div.destinationAirport div.airportSelect")).click();
String xpath = "//div[contains(#class, 'destinationAirport')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
and you call them like
driver.get("https://www.club18-30.com/club18-30");
setDepartureAirport("(MAN)");
setDestinationAirport("(IBZ)");
I would suggest that you use the 3-letter airport codes for your search, e.g. "(MAN)" for Manchester. That will be unique to each airport but you can use any unique part of the text.

JAVA - is it possible to filter the sub elements of JSON Object that is large & recursive ??

I want some help to find a quick solution for my problem. Given a json object that is large with a recursive model. I want to list the JSON sub elements & its immediate parent Object( only the sub object which satisfies the given key value condition).
Ex :
{
Object : {
id : "0001",
parent:"A",
child: {
id:"0001A",
Country:"US",
parent:"B",
child:{
id:"0001AA",
Country:"UK",
parent:"C",
child:{
id:"0000AAA",
Country:"US",
parent:"D",
child:{
.........
}
}
}
}
}
}
I want to list the id's of the subObject whose country is 'US' and it's parent id..
is there available any readymade plugins to handle these kind of scenarios in JAVA , without using object mappers/custom class objects..
Ps provide any possible idea ..
Yes, it is possible write code using the Jackson Tree Model API which would traverse a JSON tree and select the nodes that satisfy criteria. Here is an example:
public class JacksonTree2 {
public static final String JSON = "{\"Ex\" : {\"Object\" : {\n" +
" \"id\" : \"0001\",\n" +
" \"parent\":\"A\",\n" +
" \"child\": {\n" +
" \"id\":\"0001A\",\n" +
" \"Country\":\"US\",\n" +
" \"parent\":\"B\",\n" +
" \"child\":{\n" +
" \"id\":\"0001AA\",\n" +
" \"Country\":\"UK\",\n" +
" \"parent\":\"C\",\n" +
" \"child\":{\n" +
" \"id\":\"0000AAA\",\n" +
" \"Country\":\"US\",\n" +
" \"parent\":\"D\",\n" +
" \"child\":{\n" +
" \n" +
" }\n" +
" }\n" +
" }\n" +
"\t}\n" +
"}}}";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(JSON);
for (JsonNode node : root.findParents("Country")) {
if ("UK".equals(node.get("Country").asText())) {
System.out.println(node.get("id"));
break;
}
}
}
}
Output:
"0001AA"

Categories

Resources