Test cases using mockito - junit

I have below method of a class.
public Response getProb(long Id) throws ResourceException
{
final Response response = new Response();
JSONObject headerObject = new JSONObject();
String message = null;
int status = 0;
try
{
JSONObject getProb = new JSONObject();
getProb.put("id", Id);
if (commonDao.validateIdCheck(getProb))
{
headerObject.put(CommonConstants.LASTMOD_DATE, commonDao.lastModDate(Id));
response.setResource(headerObject);
message="Retuned Successfully";
}
response.setStatus(message, status);
}
catch (JSONException exception)
{
throw new ResourceException(CommonErrorConstants.JSON_EXCEPTION, exception);
}
catch (ResourceException exception)
{
throw exception;
}
catch (Exception exception)
{
throw new ResourceException(CommonErrorConstants.GENERAL_EXCEPTION, exception);
}
return response;
}
what will be the junit test cases using mockito which will give 100% code coverage.

These are the cases you can test and achieve 100% coverage:
validateIdCheck returns true
validateIdCheck returns false
your try block throws JSONException
your try block throws ResourceException
your try block throws Exception
a success case where you return a response

Related

Junit test cases for delete operation with try and catch block - handling Exception

public UserNoteDefination deleteByNoteCd (UserNoteDefination request, LogDTO log) {
log.setComponent("ClientRequestService.deleteByNoteCd");
UserNoteDefination response new UserNoteDefination();
String tabllame = request.getTabName();
String noteCd-request.getNoteCd();
if (tabName.equalsIgnoreCase("UND_TABLE"))
{
try
userNoteDefRepository.deleteById(noteCd);
response.setMsg("Completed");
log.setPayload("[FROM:UI] clientRequest:Delete Successfully");
loggingService.log(GuiServiceConstants.INFO LEVEL, log);
}
catch (Exception e){
response.setMsg("Error");
log.setPayload("[FROM:UI] clientRequest:Error occured while delete");
loggingService.log(GuiServiceConstants.ERROR LEVEL, log);
}
return response;
}
This is my junit code in mockito
#Test public void deleteByNoteCd() throws Exception {
LogDTO log = new LogDTO(); log.setComponent("ClientRequestService.getClientRequest");
UserNoteDefination response = new UserNoteDefination();
response.setNoteCd("TEST7");
response.setMsg("Completed");
response.setTabName("UND TABLE");
UserNoteDefination rval - service.deleteByNoteCd(response, log);
assertNotNull(rval);
}
I'm unable to cover the exception part. Cab someone help

How to handle IOException in Spring webflux?

I am trying to retreive byte[] from my Mono but using getBytes() method it shows unhandled IOException. How do I handle it in my reactive code?
My service layer
public HttpStatus excel(Mono<MultipartFile> filePartMono) {
Excel t = new Excel();
t.setExcel(filePartMono.map(filepart-> {
try {
return filepart.getBytes();
} catch (IOException e) {
System.out.println(e);
}
return new **byte[];** //doing this here it shows array initializer expected what does it mean
}));
excelRepository.save(t);
return HttpStatus.ACCEPTED>;

java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference

Every time I open my app it crashes because of this error I dont know what should I do please help me... I have also attached logcat screen shot below and the java class in which the error is comming.
DataParser.java:
public class DataParser {
private HashMap<String,String> getPlace(JSONObject googlePlacesJson){
HashMap<String,String> googlePlaceMap=new HashMap<>();
String placeName="-NA-";
String vicinity="-NA-";
String latitude="";
String logitude="";
String reference="";
List<HashMap<String,String>> placesList=new ArrayList<>();
try {
if(!googlePlacesJson.isNull("name")){
placeName=googlePlacesJson.getString("name");
}
if (!googlePlacesJson.isNull("vicinity")){
vicinity=googlePlacesJson.getString("vicinity");
}
latitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
logitude=googlePlacesJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference=googlePlacesJson.getString("reference");
googlePlaceMap.put("name",placeName);
googlePlaceMap.put("vicinity",vicinity);
googlePlaceMap.put("lat",latitude);
googlePlaceMap.put("lng",logitude);
googlePlaceMap.put("reference",reference);
} catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;
}
private List<HashMap<String,String>> getPlaces(JSONArray jsonArray){
long count;
count=jsonArray.length(); // error comes on this line
List<HashMap<String,String>> placesList=new ArrayList<>();
HashMap<String,String> placeMap=null;
for(int i=0;i<count;i++){
try {
placeMap=getPlace((JSONObject) jsonArray.get(i));
placesList.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}
this is the screen shot my my log cat:
The problem is somewhere in here:
public List<HashMap<String,String>> parse(String jsonData){
JSONArray jsonArray=null;
JSONObject jsonObject;
try {
jsonObject=new JSONObject(jsonData);
jsonArray=jsonObject.getJSONArray("results"); // !!! this line here !!!
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
getJSONArray("results"); returns null and that's causing problems later (NullPointerException).
What you should do:
Check your JSON for syntax errors.
Place a breakpoint at the getJSONArray() line and take a look at jsonData and jsonObject if everything is, as it should be.
The array you want to retrieve is probably not valid or not in the jsonData at all.
i would start by validating if the jsonArray is null before running the entire method. or:
if (jsonArray != null)
count=jsonArray.length();
else count = 0;
then debug to find out why you are calling that method with a null object.

Json Parse Failed- javafx

I am writing javafx app
I try to sava and load data using JSON
#FXML
private void OpenEvent(ActionEvent event) throws IOException, ParseException, Exception {
String jsonString = new String();
FileReader fileReader = new FileReader("test.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println("Check open event here");
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString += inputLine;
}
bufferedReader.close();
System.out.println(jsonString);
//GOOD HERE
JSONArray jlist;
try {
jlist = parseJsonArray(jsonString);
} catch (Exception ex) {
throw ex;
}
for (Object e : jlist) {
try {
JSONObject jentryParsed = (JSONObject) e;
LocalEvent entry = new LocalEvent();
entry.initFromJsonString(jentryParsed.toJSONString());
} catch (Exception ex) {
throw ex;
}
}
}
public JSONArray parseJsonArray(String jsonString) throws Exception {
JSONArray jlist;
JSONParser parser = new JSONParser();
System.out.println("Check parse here");
System.out.println(jsonString);
try {
jlist = (JSONArray) parser.parse(jsonString);
} catch (Exception ex) {
throw ex;
}
System.out.println("parsed finished");
if (jlist == null) {
System.out.println("jlist is null");
return null;
} else {
return jlist;
}
}
and here is my JSON file
[{"Description":"11111","Name":"11111","Datetime":2016-04-27},{"Description":"2222","Name":"2222","Datetime":2016-04-14}]
error:
Caused by: Unexpected token VALUE(-4) at position 54.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at todolist.MainController.parseJsonArray(MainController.java:276)
at todolist.MainController.OpenEvent(MainController.java:250)
... 50 more
It seems the json parse is failed.
is here anything wrong with my JSON file?
Thanks!!!!!!!
or the parse cannot recognize "-" in the datetime??

Parameter passing via httpgetClient

I need to hit the URL and get the response, but through this method I can get only one message whereas I want to pass multiple values as a response.
Here is the method:
public String getOutputFromUrl(String url)
{
Log.d("in getOutputFromUrl", "getOutputFromUrl");
String[] output = null;
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.d("in UnsupportedEncodingException", e.toString());
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("in geClientProtocolExceptiontOutputFromUrl", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("in getOutputFromUrl", e.toString());
e.printStackTrace();
}
Log.d("in getOutputFromUrl:output===>>", output);
return output;
}
I want the return type of the method to be String[] or object of any class ,but
output = EntityUtils.toString(httpEntity)
This line accepts only a string; no other object or string array, so I can't keep multiple values in this output variable passed as response from the URL link