HTTP Error 400 Bad request - java

I have an application (Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations) , integrating Spring with Hibernate using annotation based configuration.
Here my controller:
#Controller
public class RestController {
#RequestMapping(value = { "/restCallBack" }, method = RequestMethod.GET)
#ResponseBody
public String performCallBack(#RequestBody RestCallBack restCallBack) {
Preconditions.checkNotNull( restCallBack );
return "computerList";
}
but when I put this on the browser I get a 400:
http://localhost:8080/myApp/restCallBack?devideId=devideId&time=time&duplicate=duplicate&snr=snr&station=station&data=data&avgSignal=avgSignal&lat=lat&lng=lng&rssi=rssi&seqNumber=seqNumber
Here the RestCallBack class
public class RestCallCallBack {
private String devideId;
private String time;
private String duplicate;
private String snr;
private String station;
private String data;
private String avgSignal;
private String lat;
private String lng;
private String rssi;
private String seqNumber;
public String getDevideId() {
return devideId;
}
public void setDevideId(String devideId) {
this.devideId = devideId;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDuplicate() {
return duplicate;
}
public void setDuplicate(String duplicate) {
this.duplicate = duplicate;
}
public String getSnr() {
return snr;
}
public void setSnr(String snr) {
this.snr = snr;
}
public String getStation() {
return station;
}
public void setStation(String station) {
this.station = station;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getAvgSignal() {
return avgSignal;
}
public void setAvgSignal(String avgSignal) {
this.avgSignal = avgSignal;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getRssi() {
return rssi;
}
public void setRssi(String rssi) {
this.rssi = rssi;
}
public String getSeqNumber() {
return seqNumber;
}
public void setSeqNumber(String seqNumber) {
this.seqNumber = seqNumber;
}
}

Based on the example request query string, it seems like you are attempting to pass request parameters to the server rather than a request body. If so, take a look at #RequestParam, e.g.
#Controller
public class RestController {
#RequestMapping(value = { "/restCallBack" }, method = RequestMethod.GET)
#ResponseBody
public String performCallBack(#RequestParam("devideId") String devideId,
#RequestParam("time") String time,
#RequestParam("duplicate") String duplicate,
/* more request params... */ {
RestCallCallBack restCallCallBack = new RestCallCallBack();
restCallCallBack.setDevideId(devideId);
restCallCallBack.setTime(time);
restCallCallBack.setDuplicate(duplicate);
// set more params...
// perform validation
return "computerList";
}
}
You can also specify which params are optional by by setting the #RequestParam's required attribute to false.
More information available in the Binding request parameters to method parameters with #RequestParam paragraph in the Spring Reference docs.

Related

Receive array of objects in JSON by Spring Boot RestApi Controller

I want to send array of objects like this to Spring REST Controller:
{
"measureList": [
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:51.787535Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
},
{
"apiKey": "exampleKEY",
"stationId": "abcdef123",
"date": "2022-02-18T17:43:53.254309Z",
"temp": "20.5",
"humidity": "60.4",
"pressure": "1020.5",
"pm25": "100.0",
"pm25Corr": "150.0",
"pm10": "90.0"
}
]
}
I have created NewMeausurePackageDto like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
import java.util.List;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getNewMeasureListDto() {
return measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
NewMeasureDto class:
package com.weather.server.domain.dto;
public class NewMeasureDto {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
//station_id
public NewMeasureDto() {
}
private NewMeasureDto(Builder builder){
apiKey = builder.apiKey;
stationId = builder.stationId;
date = builder.date;
temp = builder.temp;
humidity = builder.humidity;
pressure = builder.pressure;
pm25 = builder.pm25;
pm10 = builder.pm10;
pm25Corr = builder.pm25Corr;
}
public String getApiKey() {
return apiKey;
}
public String getStationID() {
return stationId;
}
public String getDate() {
return date;
}
public String getTemp() {
return temp;
}
public String getHumidity() {
return humidity;
}
public String getPressure() {
return pressure;
}
public String getPm25() {
return pm25;
}
public String getPm10() {
return pm10;
}
public String getPm25Corr() {
return pm25Corr;
}
public static final class Builder {
private String apiKey;
private String stationId;
private String date;
private String temp;
private String humidity;
private String pressure;
private String pm25;
private String pm10;
private String pm25Corr;
public Builder() {
}
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
public Builder stationID(String stationId) {
this.stationId = stationId;
return this;
}
public Builder date(String date) {
this.date = date;
return this;
}
public Builder temp(String temp) {
this.temp = temp;
return this;
}
public Builder humidity(String humidity) {
this.humidity = humidity;
return this;
}
public Builder pressure(String pressure){
this.pressure = pressure;
return this;
}
public Builder pm25(String pm25){
this.pm25 = pm25;
return this;
}
public Builder pm10(String pm10){
this.pm10 = pm10;
return this;
}
public Builder pm25Corr(String pm25Corr){
this.pm25Corr = pm25Corr;
return this;
}
public NewMeasureDto build() {
return new NewMeasureDto(this);
}
}
}
And request mapping in RestController:
#PostMapping(value="/new-measure-package") //addStation id
public ResponseEntity<Void> newMeasure(#RequestBody NewMeasurePackageDto measureList){
//if api key is valid
return measureService.saveMeasurePackage(measureList.getNewMeasureListDto()) ? new ResponseEntity<>(HttpStatus.OK) :
new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
With this code all I got is error about null measureList in Service function when trying to iterate over the list. I tried changing #RequestBody to
List<NewMeasureDto> measureList, and to Map<String, NewMeasureDto> measureList but still measureList is null or empty.
Thanks to ShaharT suggestion I found the answer.
There was missing setter in NewMeasurePackageDto, the class should look like this:
package com.weather.server.domain.dto;
import java.util.ArrayList;
public class NewMeasurePackageDto {
private ArrayList<NewMeasureDto> measureList;
public NewMeasurePackageDto(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
public NewMeasurePackageDto() {
}
public ArrayList<NewMeasureDto> getMeasureList() {
return measureList;
}
public void setMeasureList(ArrayList<NewMeasureDto> measureList) {
this.measureList = measureList;
}
#Override
public String toString() {
return "NewMeasurePackageDto{" +
"measureList=" + measureList +
'}';
}
}
Conclusion is: when dealing with object of arrays in JSON, there must be setter method for variable storing list in DTO.

How can I write Junit Test case which takes URI as input?

I am Trying to write test case for a method which takes URI as input and maps with modelmapper.
however, I am getting null pointer exception for this.
I have added every possible implementaion of class which I want to test.
if you guy's need more for compilation tell me in comment section.
this one is actual implementation which I want to mock
#Override
public ApplicationScanConfigDTO getApplicationScanConfig(int account_id, String appAppScanConfigId) {
URI getUri = UriComponentsBuilder.fromPath("/").pathSegment("api/scheduleOnDemand")
.queryParam("Account_Id", account_id).queryParam("applicationConfigScanId", appAppScanConfigId).build()
.toUri();
return modelMapper.map(apiClient.getOperation(getUri, Object.class), ApplicationScanConfigDTO.class);
}
This is what I was trying
#Test
void testGetApplicationScanConfig() throws Exception {
URI getUri = new URI("/api/scheduleOnDemand?Account_Id=1&applicationConfigScanId=1");
modelmapper.map(restTemplate.getForEntity(getUri, JSONObject.class), ApplicationScanConfigDTO.class);
}
apiclient implementation
#Override
public <R> R getOperation(URI uri, Class<R> rClasss) {
URI builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
.path(uri.getPath())
.query(uri.getQuery())
.build()
.toUri();
return restTemplate.getForObject(builder, rClasss);
}
ApplicationConfigDTO actual implementation:
public class ApplicationScanConfigDTO {
private Integer id;
private String serverName;
private Integer accountId;
private String ipAddress;
private String subnetRange;
private Integer credentialId;
private String credentialName;
private String os;
private List<String> ibmLibrary;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getSubnetRange() {
return subnetRange;
}
public void setSubnetRange(String subnetRange) {
this.subnetRange = subnetRange;
}
public Integer getCredentialId() {
return credentialId;
}
public void setCredentialId(Integer credentialId) {
this.credentialId = credentialId;
}
public String getCredentialName() {
return credentialName;
}
public void setCredentialName(String credentialName) {
this.credentialName = credentialName;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public List<String> getIbmLibrary() {
return ibmLibrary;
}
public void setIbmLibrary(List<String> ibmLibrary) {
this.ibmLibrary = ibmLibrary;
}
}

Deserialize XML and get value using Java

When I use a distance API I get this response:
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2020 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>df8ee9b6422846f0b97644c0a631deb8|DU00000D71|0.0.0.0|DU000005EC, DU00000480|Ref A: F00DC0285E97417B99490A8C98E65E31 Ref B: DB3EDGE1608 Ref C: 2020-06-09T18:53:54Z|Ref A: 69E0F633DF6448A89B2B904773DF19AB Ref B: DB3EDGE0807 Ref C: 2020-06-09T18:53:54Z</TraceId>
<ResourceSets>
<ResourceSet>
<EstimatedTotal>1</EstimatedTotal>
<Resources>
<Route>
<Id>v69,h1509963868,i0,a2,cen-US,dAAAAAAAAAAA1,y0,s1,m1,o1,t4,wWriswmZmQkBa9bnail0kQA2~BFnWzEBwiKgBBH_gASHtAT8A0~VHVuaXMsIFR1bmlzaWE1~~~~v11,w-Ki_XmFfQUC94xQdyYUlQA2~BFnWzEBYRLoBBH_gAc1znT4B0~U2ZheCwgVHVuaXNpYQ2~~~~v11,k1</Id>
<BoundingBox>
<SouthLatitude>34.74499</SouthLatitude>
<WestLongitude>10.18235</WestLongitude>
<NorthLatitude>36.800014</NorthLatitude>
<EastLongitude>10.76493</EastLongitude>
</BoundingBox>
<DistanceUnit>Kilometer</DistanceUnit>
<DurationUnit>Second</DurationUnit>
<TravelDistance>271.101</TravelDistance>
...
I want to get the value of TravelDistance.
If possible a full code because I have been trying with this for long time and no solution.
You can use XmlMapper of jackson to de/serialize your XML.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.8</version>
</dependency>
so you shall need to create an instance of it and deserialize as follows :
XmlMapper mapper = new XmlMapper();
Response value = xmlMapper.readValue("<Response>..</Response>", Response.class);
So you will need to create your object model that reflects your XML.
public class Response {
private String Copyright;
private String BrandLogoUri;
private String StatusCode;
private String StatusDescription;
private String AuthenticationResultCode;
private String TraceId;
ResourceSets ResourceSetsObject;
// Getter Methods
public String getCopyright() {
return Copyright;
}
public String getBrandLogoUri() {
return BrandLogoUri;
}
public String getStatusCode() {
return StatusCode;
}
public String getStatusDescription() {
return StatusDescription;
}
public String getAuthenticationResultCode() {
return AuthenticationResultCode;
}
public String getTraceId() {
return TraceId;
}
public ResourceSets getResourceSets() {
return ResourceSetsObject;
}
// Setter Methods
public void setCopyright(String Copyright) {
this.Copyright = Copyright;
}
public void setBrandLogoUri(String BrandLogoUri) {
this.BrandLogoUri = BrandLogoUri;
}
public void setStatusCode(String StatusCode) {
this.StatusCode = StatusCode;
}
public void setStatusDescription(String StatusDescription) {
this.StatusDescription = StatusDescription;
}
public void setAuthenticationResultCode(String AuthenticationResultCode) {
this.AuthenticationResultCode = AuthenticationResultCode;
}
public void setTraceId(String TraceId) {
this.TraceId = TraceId;
}
public void setResourceSets(ResourceSets ResourceSetsObject) {
this.ResourceSetsObject = ResourceSetsObject;
}
}
public class ResourceSets {
ResourceSet ResourceSetObject;
// Getter Methods
public ResourceSet getResourceSet() {
return ResourceSetObject;
}
// Setter Methods
public void setResourceSet(ResourceSet ResourceSetObject) {
this.ResourceSetObject = ResourceSetObject;
}
}
public class ResourceSet {
private String EstimatedTotal;
Resources ResourcesObject;
// Getter Methods
public String getEstimatedTotal() {
return EstimatedTotal;
}
public Resources getResources() {
return ResourcesObject;
}
// Setter Methods
public void setEstimatedTotal(String EstimatedTotal) {
this.EstimatedTotal = EstimatedTotal;
}
public void setResources(Resources ResourcesObject) {
this.ResourcesObject = ResourcesObject;
}
}
public class Resources {
Route RouteObject;
// Getter Methods
public Route getRoute() {
return RouteObject;
}
// Setter Methods
public void setRoute(Route RouteObject) {
this.RouteObject = RouteObject;
}
}
public class Route {
private String Id;
BoundingBox BoundingBoxObject;
private String DistanceUnit;
private String DurationUnit;
private String TravelDistance;
// Getter Methods
public String getId() {
return Id;
}
public BoundingBox getBoundingBox() {
return BoundingBoxObject;
}
public String getDistanceUnit() {
return DistanceUnit;
}
public String getDurationUnit() {
return DurationUnit;
}
public String getTravelDistance() {
return TravelDistance;
}
// Setter Methods
public void setId(String Id) {
this.Id = Id;
}
public void setBoundingBox(BoundingBox BoundingBoxObject) {
this.BoundingBoxObject = BoundingBoxObject;
}
public void setDistanceUnit(String DistanceUnit) {
this.DistanceUnit = DistanceUnit;
}
public void setDurationUnit(String DurationUnit) {
this.DurationUnit = DurationUnit;
}
public void setTravelDistance(String TravelDistance) {
this.TravelDistance = TravelDistance;
}
}
public class BoundingBox {
private String SouthLatitude;
private String WestLongitude;
private String NorthLatitude;
private String EastLongitude;
// Getter Methods
public String getSouthLatitude() {
return SouthLatitude;
}
public String getWestLongitude() {
return WestLongitude;
}
public String getNorthLatitude() {
return NorthLatitude;
}
public String getEastLongitude() {
return EastLongitude;
}
// Setter Methods
public void setSouthLatitude(String SouthLatitude) {
this.SouthLatitude = SouthLatitude;
}
public void setWestLongitude(String WestLongitude) {
this.WestLongitude = WestLongitude;
}
public void setNorthLatitude(String NorthLatitude) {
this.NorthLatitude = NorthLatitude;
}
public void setEastLongitude(String EastLongitude) {
this.EastLongitude = EastLongitude;
}
}

how to convert string into Json and extrat from it info

I'm using retrofit2 and Rxjava2 to insert/get information from mongodb and nodeJs server, for now, I receive all data as a string but I want to get hole collection Infos from my base so I need to convert string to JSON and get each information.
My code to receive data:
1- Service:
#POST("collect/get")
#FormUrlEncoded
Observable<String> getcollection(#Field("selector") String selector);
2-RetrofitClient:
if(instance == null){
instance = new Retrofit.Builder()
.baseUrl("http://transportor.ddns.net:3000/")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create()).build();
}
3- Recieve function
private void getallcollection(String selector) {
compositeDisposable.add(myServices.getcollection(selector)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<String>(){
#Override
public void accept(String s) throws Exception {
Log.d("infos",s);
}
}));
}
I'm already prepared Collection class:
public class col {
private String creator;
private String emailcol;
private String date_creation_col;
private String nom_col;
private String long_col;
private String lat_col;
private String tel_fix_col;
private String tel_mobile_col;
private String creatorcreator;
private String heure_matin_col;
private String heure_apresmatin_col;
private String type;
private String imagePath;
public col(String creator, String emailcol, String date_creation_col, String nom_col, String long_col, String lat_col, String tel_fix_col, String tel_mobile_col, String creatorcreator, String heure_matin_col, String heure_apresmatin_col, String type, String imagePath) {
this.creator = creator;
this.emailcol = emailcol;
this.date_creation_col = date_creation_col;
this.nom_col = nom_col;
this.long_col = long_col;
this.lat_col = lat_col;
this.tel_fix_col = tel_fix_col;
this.tel_mobile_col = tel_mobile_col;
this.creatorcreator = creatorcreator;
this.heure_matin_col = heure_matin_col;
this.heure_apresmatin_col = heure_apresmatin_col;
this.type = type;
this.imagePath = imagePath;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getEmailcol() {
return emailcol;
}
public void setEmailcol(String emailcol) {
this.emailcol = emailcol;
}
public String getDate_creation_col() {
return date_creation_col;
}
public void setDate_creation_col(String date_creation_col) {
this.date_creation_col = date_creation_col;
}
public String getNom_col() {
return nom_col;
}
public void setNom_col(String nom_col) {
this.nom_col = nom_col;
}
public String getLong_col() {
return long_col;
}
public void setLong_col(String long_col) {
this.long_col = long_col;
}
public String getLat_col() {
return lat_col;
}
public void setLat_col(String lat_col) {
this.lat_col = lat_col;
}
public String getTel_fix_col() {
return tel_fix_col;
}
public void setTel_fix_col(String tel_fix_col) {
this.tel_fix_col = tel_fix_col;
}
public String getTel_mobile_col() {
return tel_mobile_col;
}
public void setTel_mobile_col(String tel_mobile_col) {
this.tel_mobile_col = tel_mobile_col;
}
public String getCreatorcreator() {
return creatorcreator;
}
public void setCreatorcreator(String creatorcreator) {
this.creatorcreator = creatorcreator;
}
public String getHeure_matin_col() {
return heure_matin_col;
}
public void setHeure_matin_col(String heure_matin_col) {
this.heure_matin_col = heure_matin_col;
}
public String getHeure_apresmatin_col() {
return heure_apresmatin_col;
}
public void setHeure_apresmatin_col(String heure_apresmatin_col) {
this.heure_apresmatin_col = heure_apresmatin_col;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Actually I received all data and console show me : [{"_id":"5e22074673c926147c3a73f5","date_creation_col":"17-01-2020","creator":"Alaeddine","emailcol":"amir#gmail.com","nom_col":"amir","long_col":"10.179326869547367","lat_col":"36.83353893150942","tel_fix_col":"123","tel_mobile_col":"1234","adress_col":"rue Paris mision 34","heure_matin_col":"7","heure_apresmatin_col":"5","type":"collection","imagePath":"mmmmmmmmmmmm"}]
I want to know how to extract for example creator from this Json.
You can use a third-party JSON parser, like Google GSON, as you're already developing for Android. Java does not seem to contain a built-in JSON parser.
See this answer.

how to write junit test cases for Row Mapper class in spring

Hi This is my Row Mapper class.
public class UserRowMapper implements RowMapper<UserData> {
#Override
public UserData mapRow(ResultSet resultSet, int line) throws SQLException {
UserData userData = new UserData();
try
{
userData.setUserID(resultSet.getString("User_ID"));
userData.setUserName(resultSet.getString("User_Name"));
userData.setUserPassword(resultSet.getString("User_Password"));
userData.setUserRole(resultSet.getString("User_Role"));
userData.setUserStatus(resultSet.getString("User_Status"));
userData.setUserLogStatus(resultSet.getString("UserLog_Status"));
userData.setUserAccountName(resultSet.getString("User_AccountName"));
userData.setUserAccountID(resultSet.getString("User_AccountID"));
userData.setUserEmailID(resultSet.getString("User_EmailID"));
userData.setUserPasswordStatus(resultSet.getString("User_Password_ExpiryStatus"));
userData.setUserIDStatus(resultSet.getString("User_ID_Status"));
userData.setAcatTenantID(resultSet.getLong("acatTenant_ID"));
userData.setUserRoleCode(resultSet.getLong("User_Role_Code"));
userData.setUserSkillSetCode(resultSet.getLong("User_SkillSet_Code"));
userData.setUserAccountCode(resultSet.getLong("User_Account_Code"));
return userData;
}
catch (EmptyResultDataAccessException e)
{
return null;
}
}
}
and this is my Model class.
public class UserData {
private String userID;
private String userPassword;
private String userRole;
private String userStatus;
private String userLogStatus;
private String userName;
private String userAccountName;
private String userAccountID;
private String userIDStatus;
private String userPasswordStatus;
private String userEmailID;
private String userAdminID;
private String deactivationComment;
private String reqPageID;
private String userSessionID;
private String reqFunctionalityID;
private long userAccountCode;
private long userRoleCode;
private long userSkillSetCode;
private long acatTenantID;
public long getUserAccountCode() {
return userAccountCode;
}
public void setUserAccountCode(long userAccountCode) {
this.userAccountCode = userAccountCode;
}
public long getUserRoleCode() {
return userRoleCode;
}
public void setUserRoleCode(long userRoleCode) {
this.userRoleCode = userRoleCode;
}
public long getUserSkillSetCode() {
return userSkillSetCode;
}
public void setUserSkillSetCode(long userSkillSetCode) {
this.userSkillSetCode = userSkillSetCode;
}
public long getAcatTenantID() {
return acatTenantID;
}
public void setAcatTenantID(long acatTenantID) {
this.acatTenantID = acatTenantID;
}
public String getReqFunctionalityID() {
return reqFunctionalityID;
}
public void setReqFunctionalityID(String reqFunctionalityID) {
this.reqFunctionalityID = reqFunctionalityID;
}
public String getReqPageID() {
return reqPageID;
}
public void setReqPageID(String reqPageID) {
this.reqPageID = reqPageID;
}
public String getUserSessionID() {
return userSessionID;
}
public void setUserSessionID(String userSessionID) {
this.userSessionID = userSessionID;
}
public String getUserAdminID() {
return userAdminID;
}
public void setUserAdminID(String userAdminID) {
this.userAdminID = userAdminID;
}
public String getDeactivationComment() {
return deactivationComment;
}
public void setDeactivationComment(String deactivationComment) {
this.deactivationComment = deactivationComment;
}
public String getUserIDStatus() {
return userIDStatus;
}
public void setUserIDStatus(String userIDStatus) {
this.userIDStatus = userIDStatus;
}
public String getUserPasswordStatus() {
return userPasswordStatus;
}
public void setUserPasswordStatus(String userPasswordStatus) {
this.userPasswordStatus = userPasswordStatus;
}
public String getUserEmailID() {
return userEmailID;
}
public void setUserEmailID(String userEmailID) {
this.userEmailID = userEmailID;
}
public String getUserAccountID() {
return userAccountID;
}
public void setUserAccountID(String userAccountID) {
this.userAccountID = userAccountID;
}
public String getUserAccountName() {
return userAccountName;
}
public void setUserAccountName(String userAccountName) {
this.userAccountName = userAccountName;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getUserLogStatus() {
return userLogStatus;
}
public void setUserLogStatus(String userLogStatus) {
this.userLogStatus = userLogStatus;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
The above classes are my Row Mapper and Model class.i do not know how to write junit test class for Row Mapper class .please any one guide me how to write junit test for these classes.
Hi here is my Junit test code for above classes.
public class UserRowMapperTest {
UserRowMapper userRowMapper=null;
#Before
public void runBeforeEachTest(){
userRowMapper= new UserRowMapper();
}
#After
public void runAfterEachTest(){
userRowMapper=null;
}
#Test
public void testMapRow(){
userRowMapper.mapRow(resultSet, line);
}
}
From my point of view there is nothing to test here.
You should create unit tests only for the methods which have some business logic. I don't see the reason to test the methods which are using just getters and setters because in general they don't do anything.
However, if you want just to practice this is the advice what you could do for the unit test. First of all check some questions on how to write the unit tests because it feels like you don't understand what you need/want to achieve.
In general this is the sketch of what you want:
#Test
public void testMapRow(){
// SETUP SUT
UserRowMapper userRowMapper = new UserRowMapper()
// fill (prepare) in the Object that you want to pass to a method.
ResultSet resultSet = createResultSet();
// EXERCISE
UserData resultData = userRowMapper.mapRow(resultSet, line);
// VERIFY
Assert.assertEquals(expectedValue, resultData.getSomeValue())
}
p.s. By the way, there is no point in line parameter in this method because you don't use it.
And about the NullPointerException, please, have a look to quite popular question about it.

Categories

Resources