How to use CSV Data Set with junit request test in jmeter - junit

I have a problem and I stuck in it for two days, how can I add more than one argument constructor in “ Constructor String label” ?????
When I created my test in Junit , I create a constructor using two arguments, but in jmeter , a problem occurred and me telling that it’s impossible to create an instance because of the absence of one String Constructor. So, after that, I discover that jmeter only see one string constructor or an empty one
Please help me on this point or do you suggest another alternative to pass argument to Junit test in jmeter.
For more details, I want to automate IHM tests and at the same time measure the performance and the supporting numbers of users that connect at the same time. To do that, I create my test Case using Junit and Selenium, export the jar file into junit folder under apache jmeter, creating junit request and passing “${login}, ${password}” in Constructor String Label, and finally creating the Csv Data set config to bring login and password from txt file. But I faced the problem of “impossible to create an instance because of the absence of one String Constructor”. I try to use one String constructor with login , it works very well and bring me value form txt file, but with 2 arguments in constructor it doesn’t work because jmeter didn't support it. Do you suggest another alternative :s :s :s please Help.
This is the code i have so far:
public void test() throws InterruptedException {
driver.get(baseUrl + "/"); //clear username filed
driver.findElement(By.id("username")).clear(); //enter user name
driver.findElement(By.id("username")).sendKeys(login); //clear password
driver.findElement(By.id("password")).clear(); //enter password
driver.findElement(By.id("password")).sendKeys(password); //click on submit button
driver.findElement(By.id("submit")).click();
}

Finaly and fortunately, I found a solution to my problem. Instead of using junit test I used jmeter-java test to run diffrent session from jmeter with diffrent login and password for each session using CSV Data Set Config and this article was very useful to me :D http://www.javacodegeeks.com/2012/05/apache-jmeter-load-test-whatever-you.html/comment-page-1/#comment-8288 and instead of "testuser" in java request " ${login}" and "${password} instead of "testpasswd" to bring data from txt file related to CSV Data Set Config
And your test method will look like that (In my case i'm using selenium for test on browser)
public SampleResult runTest(JavaSamplerContext arg0) {
// TODO Auto-generated method stub
login = arg0.getParameter("login");
password=arg0.getParameter("password");
SampleResult result = new SampleResult();
boolean success = true;
result.sampleStart();
// Write your test code here.
//
driver.get(baseUrl + "/");
//clear username file
driver.findElement(By.id("username")).clear();
//enter user name
driver.findElement(By.id("username")).sendKeys(login);
//clear password
driver.findElement(By.id("password")).clear();
//enter password
driver.findElement(By.id("password")).sendKeys(password);
//click on submit button;
driver.findElement(By.id("submit")).click();
////
result.sampleEnd();
result.setSuccessful(success);
return result;
}
And getDefaultParameters
#Override
public Arguments getDefaultParameters() {
// TODO Auto-generated method stub
defaultParameters=new Arguments();
defaultParameters.addArgument("login", "ImenUser1");
defaultParameters.addArgument("password","ImenUser#");
return defaultParameters;
}

Related

Autodesk java api response mapping

We are using the forge-api-java-client. There is an issue in Model Derivatives getManifest call.
The response fails mapping with a single Message String being returned instead of the expected String Array.
Have switched to using local build of the jar, change in file Message.java to include an alternative constructor for the class setMessage
public void setMessage(String message) {
List<String> messages = new ArrayList<>();
messages.add(message);
setMessage(messages);
}
Could this change be merged into the project.
We'll check it, but as of today, that package is just under maintenance. You are welcome to submit a PR.

Xamarin Forms - Saving object to access it later

I am using Xamarin Forms with Newtonsoft.JSON and Xam.Plugin.Settings plugins to save IDevice object as JSON to use it later.
First page:
private async void SelectBluetoothDevice(object sender, SelectedItemChangedEventArgs e)
{
string device = JsonConvert.SerializeObject((IDevice) e.SelectedItem);
AppSettings.AddOrUpdateValue("device", device);
await Navigation.PopAsync();
}
Here I simply make selected item to JSON string and save it. It works like it should be.
But the problem im facing comes whenever I try to deserialize from saved string.
string device = AppSettings.GetValueOrDefault("device", "");
if (!device.Equals(""))
{
Debug.WriteLine(device);
// This line produces error
IDevice dev = JsonConvert.DeserializeObject<IDevice>(device);
settingsDeviceName.Text = dev.Name;
}
Newtonsoft.Json.JsonSerializationException: Could not create an
instance of type Plugin.BLE.Abstractions.Contracts.IDevice. Type is an
interface or abstract class and cannot be instantiated. Path
'BluetoothDevice', line 1, position 19.
So I understand that IDevice is interface and my JSON string cant be deserialized nothing but into object. Any good ideas how to workaround it? Thanks!
This line JsonConvert.DeserializeObject<IDevice>(device); basically does this:
Read the JSON in device
Try to create the type of object you want to deserialize to, in this case, IDevice
Return you the new object with all the properties filled
The problem is with step 2. You can't create an instance of an interface. So you need to deserialize to a concrete object that implements IDevice.

Assertion error expectation failure EasyMock

I have the next JUnit test, and it works fine, but finally in the verify it throws expectation failure. I think it is because the mocked PsPort is different of the PsPort that I send to the DataReader.
Is there any other way to test it?
#Test
public void testguardarMensaje() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException{
String datoTest = "1=123456";
Constructor<PsPort> constructor = PsPort.class.getDeclaredConstructor(new Class[] {String.class});
constructor.setAccessible(true);
PsPort port = constructor.newInstance("middleware.conf");
PsPort drMock;
int hash1 = datoTest.hashCode();
String hashString1 = String.valueOf(hash1);
String combinedIdDataHashString1 = datoTest +"="+ hashString1;
drMock = strictMock(PsPort.class);
byte[] datoByte = port.encriptarDesencriptarMensaje(combinedIdDataHashString1.getBytes(), Cipher.ENCRYPT_MODE);
drMock.guardarDato(datoByte);
replayAll();
int hash = datoTest.hashCode();
String hashString = String.valueOf(hash);
String combinedIdDataHashString = datoTest +"="+ hashString;
byte[] datoByte2 = port.encriptarDesencriptarMensaje(combinedIdDataHashString.getBytes(), Cipher.ENCRYPT_MODE);
DatagramPacket paquete = new DatagramPacket(datoByte2,datoByte2.length);
paquete.getData();
DataReader dr = new DataReader(port, null, 100, "=", "C:/Users/Asier/Desktop/logs/");
dr.guardarMensaje(paquete, port);
verifyAll();
}
It is really confusing that you have two port objects. What is the sense of creating a mocked drPort; when you are then giving a "real" port object to your class under test?
You see: you either create a mock and pass that down to your code under test (and then you have to setup the mock for the expected behavior; which you can afterwards verify); or you only provide "real" objects to your code under test, but then you would normally do some kind of asserts on the results of calls to "code under test".
So, in that sense, it doesn't really matter that there is at least one problem in your code:
drMock.guardarDato(datoByte);
replayAll();
There should be a call to EasyMock.expectLastCall() after the method invocation on drMock; but as said: as the mocked object isn't really used, that doesn't matter, on the one hand. Because, if you added that statement, your test would always fail; since your un-used mock would never see the calls that you specified it to see.
In order to give you some guidance; this is how you do such kind of testing in general:
SomeClassYouNeed mockedThingy = createStrict/Nice(SomeClassYouNeed.class);
expect(mockedThingy.foo()).andReturn("whatever");
mockedThingy.bar();
expectLastCall();
replay (mockedThingy);
ClassUnderTest underTest = new ClassUnderTest(mockedThingy);
underTest.doSomething();
verify(mockedThingy)
Meaning: any "object" that
a) your "class under test" needs to do its work
b) you want/have to "control" in a certain way
needs to be mocked; including a "specification" of all expected method calls.
Then you provide the mocked things to your code under test; execute the method you want to test ... to finally verify that the mock saw the behavior that you specified for it.

Using MySQL with visual studio and changing the connection at runtime

I use something like this for my application
MySqlConnection cnn = new MySqlConnection("Server=myServerAddress;" +
"Database=myDataBase;" +
"Uid=myUsername;" +
"Pwd=myPassword;");
And this changes everytime because we deploy databases with our application.
It works fine. I type in using(new connection(cnn)){ query... } and go.
And I've got it working with a dataset using a connection defined in the windows ODBC datasouce administrator.
But I'm curious, is there a way to use visual studio's dataset items using the my local test db and then change the connection of the dataset at runtime? Even better, can I use c# to programmatically add the ODBC data source at runtime?
Usually a connection string is loaded from the application exe.config file present in the same folder of the application. This connection string could be defined using the Settings tab in the project properties.
Right click on Properties of your project
Select the Settings tab (confirm the creation if you have no
settings)
Click on the ComboBox in the column type and select Connection String
Give a symbolic name to your connection
Type the connection string in the Value column (Examples at
connectionstrings.com)
Now in your project files you should have the file app.config (that becomes yourapp.exe.config) where there is a section like this
<configuration>
<connectionStrings>
<add name="MyAppConnection"
connectionString="Server=myServerAddress;Database=myDB;Uid=user;Pwd=pass;" />
</connectionStrings>
</configuration
At this point you read it in the program using
string conString = ConfigurationManager
.ConnectionStrings["MyAppConnection"]
.ConnectionString;
Instead in a dynamic situation where you want to build yourself the connection string during runtime (from user inputs, your own configuration files and so on) then you could leverage the functionality of the class MySqlConnectionStringBuilder
MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder();
msb.Server = "localhost";
msb.Port = 3306;
msb.UserID = "root";
msb.Password = "xxx";
msb.Database = "test";
MySqlConnection cnn = new MySqlConnection(msb.ConnectionString);
cnn.Open();
Of course, these literal values could be substituted by your own variables.
The documentation of this class is surprising difficult to find. The best docs are the one of the Sql Server equivalent. It is interesting that you could read a static connection string from your config file and then change only the property needed.
string conString = ConfigurationManager
.ConnectionStrings["MyAppConnection"]
.ConnectionString;
MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(conString);
msb.Database = "AnotherDB";
MySqlConnection cnn = new MySqlConnection(msb.ConnectionString);
Application connection string cannot be changed at runtime.
User settings can be changed.
Assuming you are using an application setting-property named "MyConnectionString" which holds the connection string for the entire application.
On your main Program class create a global string:
internal static string Prconnstring;
Create and save this settings.cs file:
namespace MYSOLUTIONORPROJECTNAME.Properties
{
// (Not sure where I found this solution some time ago)
// This class allows you to handle specific events on the settings class:
// The SettingChanging event is raised before a setting's value is changed.
// The PropertyChanged event is raised after a setting's value is changed.
// The SettingsLoaded event is raised after the setting values are loaded.
// The SettingsSaving event is raised before the setting values are saved.
internal sealed partial class Settings
{
public Settings()
{
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
}
private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
{
// Add code to handle the SettingChangingEvent event here.
}
private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
// Add code to handle the SettingsSaving event here.
}
public override object this[string propertyName]
{
get
{
if (propertyName == "MyConnectionString")
{
return Program.Prconnstring;
}
else
{
return base[propertyName];
}
}
set
{
base[propertyName] = value;
}
}
}
}
Before calling-opening any object that uses the connection string (examples include Forms that use datasets or other classes that use datasets created on the development enviroment) create your new connection string by any means you think. (Example: You might want to use as user name in the connection string the current user. Create the connection string using the info provided form the environment.)
Program.Prconnstring = thenewruntimeconnectionstring.
Now whenever the application tries to get MyConnectionString (which is hardcoded in the myapplicationname.config and cannot be changed) instead gets the new thenewruntimeconnectionstring you provided to Program.Prconnstring.
Be aware that the development connection string will be available-visible to final user, since it is just a text file. If you do not want this, you can change that file (will be a file named NAMEOFMYAPPLICATION.exe.config) during deployment, since the connection string hardcoded there, will be of no use for the running app. Do not delete it, just change.
Your connection string will be stored in your App.config (or c# equivalent). Say it's called MyConnectionString. Just add My.Settings("MyConnectionString")="[your new connection string]" to your entry point to change to database binding at runtime. E.g:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
My.Settings("MyConnectionString") = "server=remotedb.uk;user id=MainUser;password=2jdi38edhnche73g;database=mainDb;persistsecurityinfo=True;allowuservariables=True;defaultcommandtimeout=480;characterset=utf8mb4"
End Sub

A plain HTML Submit button passes to the controller only after the second click

I have many submit buttons in my plain HTML . The one not working is as below:- the other are as same as below
< form:submit cssClass="action-button" name="excelBTNX" value="Excel" id="excelBTNX" />
The function of the above button in the controller is to create a excel sheet and put in session(I can download it from cookies ) and returns back .
The defination of the corrosponding method in Controller is as same as for other buttons which are working fine .
The problem with this is ,it works only at even count hit .When I click for the first time the page gets refreshed . When I click for the second time , control passes to the controller and my excel comes up as cookies.
I tried to track whether the submit is working or not with javaScript code as
$(‘form’).submit(function(){
alert("event getting fired");
});
and it gives the alert for both the cases.
I have done the validation part from the controller(manually), so local inbuilt validators are not used . So I believe they are not the case.
How do I fix it ?
Controller codes:-
#RequestMapping(value = "execute.action", method = RequestMethod.POST, params = "excelBTNX")
public String excelOut(HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("mymodel") myModel model, BindingResult bindingResult, ModelMap modelmap) {
scr14(request).initializeSomeCalculation(model);// some innercalss called to manupulate model
HttpSession session = request.getSession(false);
if(1=1){//CRUD condition here true in READ mode.
model= new myModel ();
}
byte[] excel = createExcelS14(model,request);
String fileName = getExcelName() + ".xls";
String filepath = myFrameWorkUtils.createTempFile(excel, fileName);
if (session != null) {
session.setAttribute(fileDownload, filepath);
}
scr14(request).initializeSomeCalculation(model);
model.setDate(somedate);
return "myPanel";}
Here are some steps:
Check whether this issue is related to your Excel processing or whether it is something with your Controller. I assume you have something like
#RequestMapping(..., params = "excelBTNX")
public ModelAndView next(...)
{ <EXCEL FUNCTIONALITY> }
Just comment out the in the Controller and verify that the method is called every time. Please test this a let us know whether this is working.
What happens that makes you think the Controller is only called at the second click? Maybe the signs that you are looking at don't really mean that the controller is only called every second click. Please explain.
Fix if (1=1) code. = in Java is the assignment operator, == is the comparison operator. I assume you want to do a comparison. It also seems like you simplified this part of the code, but it may actually be the problem. Please post the actual code here.
I don't see anything about cookies here. It looks to me like you are creating a temporary Excel file, and setting the name of the file in the session.
session.setAttribute(fileDownload, filepath) cannot work, since the key of the session attribute map is of type String. It should probably be session.setAttribute("fileDownload", filepath).
Can you see whether there is a new temp Excel file generated with each click? You should be able to tell by the timestamp.
This may still not point to the problem, but it will certainly get us closer.