Is there a way in testNG to skip tests based on data provider input? - testng-dataprovider

For Eg:
Below is my test method and data provider. my testmethod should be skipped if data provider input is "Two".
#Test(dataprovider = "getData")
public void test(String data) {
System.out.println(data + " Executed successfully");
}
#DataProvider
public Object[][] getData(){
return new Object[][]{
{"One"},
{"Two"},
{"Three"},
{"Four"},
{"Five"}
};
}

inside your test method , you can compare the parameter data and throw a skip exception when your condition is satisfied.
#Test(dataprovider = "getData")
public void test(String data) {
if(data.equals("two")){
throw new SkipException("Test skipped as data is:"+data);
}
System.out.println(data + " Executed successfully");
}

Related

Assert null is not working as actual method changes the value

I am trying to write a Junit for a piece of code for asserting the value as null. But the value is changing on the actual call.
Main Class Code
#Activate
public void activate(ComponentContext context)
{
myNotificationSubscriber = NotificationSubscriber.newInstance(myGlobalTableNotificationService,
NotificationType.ENTITIES,
this);
setWantedSubscriptionStatus();
LOG.debug("Activating {} service", getClass().getName());
try
{
applyConfigUpdate(context, IS_ACTIVATION);
}
catch (ServiceNotAvailableException e)
{
String instanceNameWithException = COUNTER_INSTANCE_COBA.concat("-")
.concat(String.valueOf(e.getResponseCode().getResponseCode()))
.concat(e.getClass().getSimpleName());
myCounterregistrator.get()
.incrementCounter(Counter.DATAACCESS_COBA_RESPONSE_UNSUCCESSFUL.getCounterInstance(instanceNameWithException));
LOG.debug("Can not activate Component :{}", e.getMessage());
}
LOG.info("COBA Cache state is {}", myCacheState);
}
private GlobalTableRetriever getGlobalTableRetrieverer() throws ServiceNotAvailableException
{
GlobalTableRetriever tableFetcher = myGlobalTableRetriever.get();
if (tableFetcher == null)
{
throw new ServiceNotAvailableException(RETRIEVER_SERVICE_NOT_AVAILABLE_MSG, ResponseCode.COBA_READ_DATA_TEMPORARY_ERROR);
}
return tableFetcher;
}
I want to write the test for the catch block. So tried to write the test case in below.
#Test
public void testapplyConfigUpdate() throws GlobalTableException
{
exception.expect(ServiceNotAvailableException.class);
globalTableRetriever.set(null);
tableFetcher = globalTableRetriever.get();
assertThat(tableFetcher).isNull();
myTableHandler.activate(myOsgiComponentContext);
verify(myCounterRegistratorService, times(1)).incrementCounter(any(CounterInstance.class));
}
But once its entering to getGlobalTableRetrieverer method, the assertion null value is changing to original.
Why do you even need to assert that?
exception.expect(ServiceNotAvailableException.class);
already implies that tableFetcher is null.
Just try this :
#Test
public void testapplyConfigUpdate() throws GlobalTableException
{
exception.expect(ServiceNotAvailableException.class);
globalTableRetriever.set(null);
tableFetcher = globalTableRetriever.get();
}

mock.method call returns null after stubbing

I am trying to test using Mockito
my class under test is
#Service
public class DynatraceAPIServiceImpl implements DynatraceAPIService {
private String apiUrl = "someurl";
private String apiToken = "sometoken";
#Override
public CreateCustomMetricResponse createCustomMetric(CreateCustomMetricRequest request) throws MonitoringException {
logger.info("Inside create custom metric");
if (request == null) {
logger.error("create metric request is null");
throw new MonitoringException("Create metric request is null");
}
String metricId = DynatraceConstants.METRIC_ID;
String displayName = request.getDisplayName();
CreateCustomMetricResponse response = httpUtils.postCustomMetric(apiUrl + "/v1/timeseries/" + metricId, apiToken, request);
if (response == null) {
logger.error("Error in creating custom metric with name : " + displayName);
throw new MonitoringException("Error in creating custom metric with name : " + displayName);
}
logger.info("Custom metric : " + displayName + " is created successfully.");
return response;
}
}
and my Test class is :
#RunWith(MockitoJUnitRunner.class)
public class DynatraceAPIServiceImplTest {
#InjectMocks
DynatraceAPIServiceImpl dynatraceAPIServiceImpl;
#Mock
DynatraceHttpUtils httpUtilsMock;
#Mock
DynatraceMonitoringUtils monitoringUtilsMock;
#Test(expected = MonitoringException.class)
public void createCustomMetricGetsNonNullResponse() throws MonitoringException {
CreateCustomMetricRequest mockRequest = CreateCustomMetricRequest.builder()
.displayName(DISPLAY_NAME)
.types(new String[] {"test-type"})
.build();
CreateCustomMetricResponse response = CreateCustomMetricResponse.builder()
.displayName(DISPLAY_NAME)
.types(new String[] {"test-type"})
.timeseriesId(TIMESERIES_ID)
.build();
boolean val = true;
when(monitoringUtilsMock.isValidMetricIdValue(anyString())).thenReturn(val);
when(httpUtilsMock.postCustomMetric(API_URL + "/v1/timeseries/" + METRIC_ID, API_TOKEN, mockRequest)).thenReturn(response);
CreateCustomMetricResponse actualRespnose = dynatraceAPIServiceImpl.createCustomMetric(mockRequest);
//verify(httpUtilsMock, times(1)).postCustomMetric(anyString(), anyString(), any(CreateCustomMetricRequest.class));
//assertEquals(actualRespnose.getDisplayName(), DISPLAY_NAME);
}
}
Here, when I execute the tests, it always end up having the response value to be null in line
CreateCustomMetricResponse response = httpUtils.postCustomMetric(apiUrl + "/v1/timeseries/" + metricId, apiToken, request);
Even if I have used when() statement to return response as I have created, it is returning null.
Really appreciate if someone can let me know what is wrong here. Thanks.
That normally happens when the params your production code uses differ from the ones that you stubbed the call with, an easy way to find out is to write the test like this
when(httpUtilsMock.postCustomMetric(any(), any(), any())).thenReturn(response);
CreateCustomMetricResponse actualRespnose = dynatraceAPIServiceImpl.createCustomMetric(mockRequest);
verify(httpUtilsMock).postCustomMetric(API_URL + "/v1/timeseries/" + METRIC_ID, API_TOKEN, mockRequest);
If you do that, you'll get a nicer error showing the difference between what your code did and what you verified it for
A better approach in general is to use 'strict stubs' so if your code does anything different to what you stubbed the mock for you'll get a nice error telling you what, where and why

batch update for updating multiple records in spring mvc with mysql

I have an issue that suppose I have say 100 records initially, and I shown them on UI as a list of users. Now I have given the provision to deactivate number users by clicking "deactivate" button which is placed against every single record, I then capture all the "deactivated" users in a list and send it to the DAO layer.[the logic of deactivating user is just to set 'isDeleted' flag to true, i.e.soft delete So it is as good as I am updating multiple records whose Ids I have Placed into the list],There is a simple solution that, write a for loop->iterate through the list-> and for each record fire a query to update isDeleted flag to true, but its not feasible solution if I have say 5000 records to be deleted at once. I have heard and implemented the batchUpdate concept for "Inserting" multiple records at once, but I dont understand how can I use batch Update to update several records at only one DB call, Please help, The batch update code for insertion is as follows,
private static final String INSERT_USER_PERMISSION =
"INSERT INTO permission_transaction(permissionId,userId,isDeleted) "
+ "VALUES(?,?,?)";
#Transactional
public void addPermission(final UserVO userVo, final List<PermissionVO> permissionVoList)
throws Exception {
logger.info("Adding user permission, for userId: "+userVo.getUserId());
try {
jdbc.batchUpdate(INSERT_USER_PERMISSION, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
PermissionVO permissionVo = permissionVoList.get(i);
ps.setInt(1, permissionVo.getPermissionId());
ps.setInt(2, userVo.getUserId());
ps.setBoolean(3, false);
}
#Override
public int getBatchSize() {
return permissionVoList.size();
}
});
logger.info("Exiting addPermission, for userId: "+userVo.getUserId());
}catch (Exception e) {
logger.error("Error in adding user permission: " + e.getMessage(), e);
throw e;
}
}
Hey I found the Solution, Here is what I did,
private static final String UPDATE_CLIENT_OWNER =
"UPDATE clientowner SET "
+ "clientOwnerName=?,"
+ "clientOwnerPhone=?,"
+ "clientOwnerEmail=?,"
+ "lastUpdatedOn=NOW() "
+ "WHERE clientOwnerId=?";
#Transactional
public void updateClientOwner(int clientId, List<ClientOwnerVO> clientOwnerVoList) throws Exception {
logger.info("Updating client Owner(s)");
try{
int[] count = jdbc.batchUpdate(UPDATE_CLIENT_OWNER, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ClientOwnerVO clientOwnerVO = clientOwnerVoList.get(i);
ps.setString(1, clientOwnerVO.getClientOwnerName());
ps.setString(2, VariableEncryption.encrypt(clientOwnerVO.getClientOwnerPhone(), clientOwnerVO.getCreatedOn()));
ps.setString(3, VariableEncryption.encrypt(clientOwnerVO.getClientOwnerEmail(), clientOwnerVO.getCreatedOn()));
ps.setInt(4, clientOwnerVO.getClientOwnerID());
}
#Override
public int getBatchSize() {
return clientOwnerVoList.size();
}
});
logger.info("Exiting After successfully updating "+count.toString()+" client owners");
}catch (Exception e) {
logger.error("Error in updating client owners: " + e.getMessage(), e);
throw e;
}

Error with Async_Http_Response_Handler

I am a beginner in Android development. I am developing an application which receives MySql data and then saves it in SQLite.
I am using Json for sync status so that i can show the the number unsync data as number of pending data to be synced.
The AsyncHttpResponseHandler is showing error in code as " Class 'Anonymous class derived from AsyncHttpResponseHandler method' onFailure(int, Header[], byte[],Throwable)' in 'AsyncHttpResponseHandler' ".
Now i am stuck with a problem in the code which i can't solve.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class MainActivity extends AppCompatActivity {
// DB Class to perform DB related operations
DBController controller = new DBController(this);
// Progress Dialog Object
ProgressDialog prgDialog;
HashMap<String, String> queryValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
// If users exists in SQLite DB
if (userList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.view_logtable_entry, new String[] {
"id", "time","logtitle","log" }, new int[] { R.id.id, R.id.time, R.id.logtitle, R.id.log });
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
}
// Initialize Progress Dialog properties
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Transferring Data. Please wait...");
prgDialog.setCancelable(false);
// BroadCase Receiver Intent Object
Intent alarmIntent = new Intent(getApplicationContext(), SampleBC.class);
// Pending Intent Object
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Alarm Manager Object
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// Alarm Manager calls BroadCast for every Ten seconds (10 * 1000), BroadCase further calls service to check if new records are inserted in
// Remote MySQL DB
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 5000, 10 * 1000, pendingIntent);
}
// When Options Menu is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here.
int id = item.getItemId();
// When Sync action button is clicked
if (id == R.id.refresh) {
// Transfer data from remote MySQL DB to SQLite on Android and perform Sync
syncSQLiteMySQLDB();
return true;
}
return super.onOptionsItemSelected(item);
}
// Method to Sync MySQL to SQLite DB
public void syncSQLiteMySQLDB() {
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
// Show ProgressBar
prgDialog.show();
// Make Http call to getusers.php
client.post("http://example.com:3333/syncfolder/getusers.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Hide ProgressBar
prgDialog.hide();
// Update SQLite DB with response sent by getusers.php
updateSQLite(response);
}
// When error occured
#Override
public void onFailure(int statusCode, Throwable error, String content) {
// TODO Auto-generated method stub
// Hide ProgressBar
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
public void updateSQLite(String response){
ArrayList<HashMap<String, String>> usersynclist;
usersynclist = new ArrayList<HashMap<String, String>>();
// Create GSON object
Gson gson = new GsonBuilder().create();
try {
// Extract JSON array from the response
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
// If no of array elements is not zero
if(arr.length() != 0){
// Loop through each array element, get JSON object which has userid and username
for (int i = 0; i < arr.length(); i++) {
// Get JSON object
JSONObject obj = (JSONObject) arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("time"));
System.out.println(obj.get("logtitle"));
System.out.println(obj.get("log"));
// DB QueryValues Object to insert into SQLite
queryValues = new HashMap<String, String>();
// Add userID extracted from Object
queryValues.put("id", obj.get("id").toString());
// Add userName extracted from Object
queryValues.put("time", obj.get("time").toString());
queryValues.put("logtitle", obj.get("logtitle").toString());
queryValues.put("log", obj.get("log").toString());
// Insert User into SQLite DB
controller.insertUser(queryValues);
HashMap<String, String> map = new HashMap<String, String>();
// Add status for each User in Hashmap
map.put("id", obj.get("id").toString());
map.put("status", "1");
usersynclist.add(map);
}
// Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users
updateMySQLSyncSts(gson.toJson(usersynclist));
// Reload the Main Activity
reloadActivity();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Method to inform remote MySQL DB about completion of Sync activity
public void updateMySQLSyncSts(String json) {
System.out.println(json);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("syncstatus", json);
// Make Http call to updatesyncsts.php with JSON parameter which has Sync statuses of Users
client.post("http://example.com:3333/syncfolder/updatesyncsts.php", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_LONG).show();
}
});
}
// Reload MainActivity
public void reloadActivity() {
Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(objIntent);
}
}
you should change your method signature of
onSuccess(String response)
to
onSuccess(int responseCode, Header[] responseHeaders, String responseBody)

sending arraylist from a rest service

I am new to webservices and also REST. I am trying to send a message as a post request to a rest service using rest java client.I am trying to get response of previous requests also(everything in json format). So, am storing the message objects into an arraylist and sending the list as a reponse. But I am not able to get the previous messages. Please tell me if am doing anything wrong.
This is my message model class.
public class Messages {
private String id;
private String message;
public Messages() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
the following is my webservice to receive a message object and return a json array.
#Path("/json/messages")
public class JSONMessages {
public List<Messages> list = new ArrayList<Messages>();
List<Messages> getAllMessages(Messages m){
list.add(m);
return list;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response MessageListInJSON(Messages msg) {
System.out.println("message saved");
if(!(msg.getId().equals("1"))){
String output ="Invalid User";
return Response.ok(output).build();
}
else{
return Response.ok(getAllMessages(msg)).build();
}
}
}
Finally, the following is my client side code
public class ClientPost {
public static void main(String[] args) {
try {
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource("http://localhost:8050/lab.rest.webservices/rest/json/messages/post");
//for(int i=0;i<5;i++){
String input = "{\"id\":\"1\", \"message\":\"hey there!\"}";
ClientResponse response = webResource.accept("application/json").type("application/json")
.entity(input).post(ClientResponse.class);
if (response.getStatus() !=200 ) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output+"\n");
}
catch (Exception e) {
e.printStackTrace();
}
} }
Now, what I am expecting to see is the message I sent along with the previous responses stored in the array list(which were sent by running the client multiple times manually for now) but always am ending up with only the current message.
output:
Output from Server ....
[{"id":"1","message":"hey there!"}]
To be precise, what I want as output when i run my client several times(or put the try block in loop) is as follows which i am unable to get.
Output from Server ....
[{"id":"1","message":"hey there!"},{"id":"1","message":"hey there!"},{"id":"1","message":"hey there!"},{"id":"1","message":"hey there!"}] .
Resources in JAXRS aren't singletons. That means that for each request, the class JSONMessages is instantiated. So you lose the content of the attribute list. Changing it to static could fix your problem.
There is an annotation Singleton to change this behavior. In this case the resource will be managed as singleton and not in request scope. Here is a sample:
#Singleton
#Path("/json/messages")
public class JSONMessages {
(...)
}
Otherwise, be careful of concurrent accesses on your list. See this question for more details: java concurrent Array List access.
Hope it helps you,
Thierry