The scenario is like i will fetch four data from open api end points from a json array for the first threenter code heree output. Then i kept the data in four arraylist, account no, com amount, revenue amount, mark up realized amount. Till this it works fine. Now i have to take the first index data from each of the list and use it in a test method. In this whay i would take the secound index, third indexx data from array list and use it in the sme test method. The test method will go the ui and vaidate. I have right now used a loop which executes this test method three times by taking data three times from the arraylist. Is there a different way where i can avoid the loop in test method and the test method will execute three times by taking the each index value from the arraylist.
#Test(dependsOnMethods = "getTransactionRecordDetailsForSpecificAccountNumberByDateRange")
public void verifyTransactionDetailsFromOpenAPIOnSFObject() throws InterruptedException, AWTException {enter code here
for (int i = 0; i < 3; i++) {
launchApp();
homepage = new HomePage();
companyaccountpage = new CompanyAccountPage();
homepage.navigateToCompanyAccountDetailsPage(li_AcctNo.get(i));
companyaccountpage.navigateToTransactionTableDetails();
Assert.assertEquals(companyaccountpage.getValueOfTotalComissionAmountFromTransactionTable(actual_tsDate),
li_comAmt.get(i));
Assert.assertEquals(companyaccountpage.getValueOfTotalMarkUpRealizedAmountTransactionTable(actual_tsDate),
li_markupAmt.get(i));
Assert.assertEquals(companyaccountpage.getValueOfTotalRevenueAmountFromTransactionTable(actual_tsDate),
li_revenueAmt.get(i));`enter code here`
fd.quit();
Perhaps three different test cases would be another way to do things logically too since you're testing for different details. If you're worried about code duplication, then you can make a separate function for the loop logic.
Related
I have a loop in my code which goes over a set of strings. Said strings are then passed along to several other functions.
In my tests, I'm basically emulating the flow of code and asserting at the start of each method I expect it to visit, if the string is correct.
But I can only write the test method once. Meaning that I have to do the following to catch all the different strings:
assertTrue(string.equals("test1") || string.equals("test2") || string.equals("test3") || ...);
However, there's a problem with this if one or more of those strings are not successfully passed to the list that is looped over. Since this is a chain of OR statements, it will succeed as long as there is 1 correct string, regardless of whether any of the other strings are missing. Which is a problem.
I can't emulate the loop, I can only emulate the functions receiving the data each time.
Is there a way to deal with this problem?
EDIT: some clarification.
I start out with a list of strings.
This list gets looped over, meaning every single string instance will go through a bunch of functions. And then the next string. And so on.
In the test, I can write dummies for the methods the string goes through. This means I override the behavior of the actual code and send my own custom return. This has to be correct though, since the function following that has to properly process what I just send to it.
But, when I start the test with the dummy data, it will do the loop, meaning the same function gets called multiple times, each time with a different string. I can't just do 1 test for one of the strings, because the next loop will fail on the next string.
I want to declare integers, while the program is running.
I run the program, and then I give it via System.in.println an integer and repeat this as long as I want.
I want the program to give those integers a name of a certain type for, for example a(i) or a[i], dunno, (it should be handy) and then a(i) represents the the i'th integer I gave the program.
My idea is then that I can use those elements by their name just like, if I had declared them in the first place.
For example add two integers together.
For example I defined a method add+, which waits for 2 integer and then adds them. For example I write:
add
a(2)
a(47)
(then I would get here the result.)
I don't think implementing the add function is difficult. However I don't know, how to let the program count the number of inputs or how to let it declare and use variables.
First: Welcome to programming java; it will be a long road.
Here are some hints:
Use a List<Integer> to hold the sequence of numbers entered by the user.
Actually instanciate a concreate List class, for example LinkedList<Integer>'. If you need to access the elements by index, use anArrayList`.\
Each time the user enters a number, create a new Integer and userList.add(newInteger);
Simple sample
List<Integer> userList = new LinkedList<Integer>();
for (index = 0; index < 9; ++index)
{
Integer newInteger = new Integer(index);
userList.add(newInteger);
}
for (Integer current : userList)
{
System.out.println(current);
}
Yeah, I am following the conversation.
I am just a bit frustrated, because I can't really write any interesting or practical java programs (yet), because my knowledge isn't that big yet.
First I tried to find out, if there was a way to add elements to array, because arrays seemed to me very useful, because each element of an array already has an address. I googled, and it seems that is not possible.
I might be able to use the idea with the list, but it seems to be that the length of the list has to have a limit and actually I wanted to avoid that.
This question already has answers here:
How to test randomness (case in point - Shuffling)
(11 answers)
Closed 8 years ago.
I have written a method to shuffle a String array
So the task is to implement WhiteElephant concept for a given string array of list of names.Should generate assignments to match the original elements.
I have written method to pick a random number and used a map to store the values so that each value will have a different index. But this prints out only 5 values. and i am confused now.
public static String[] generateAssignments(final String[] participants) {
Random r = new Random();
int size = participants.length;
HashMap val = new HashMap();
int change = 0;
String[] assignments = new String[6];
System.out.println("Using arrays");
for(int i=0; i<size;i++){
for(int j =0; j<size; j++){
change = r.nextInt(size);
if(val.containsValue(change) || change==i){
continue;
}
else val.put(i, change);
assignments[i] = participants[change];
System.out.println(assignments[i]);
break;
}
}
return assignments;
}
I appreciate your inputs.
Thanks,
Lucky
If your shuffle method is random (or pseudorandom) it will be near impossible to unit test since the output is non deterministic. If you allow for seeding a random number generator then you could ensure the output is consistent given the same seeds, though this doesn't show randomness.
You could also run the shuffle method a large number of times and check that each card shows up at each index an approixmately equal number of times. Over a large enough number of simulations this should help illustrate randomness.
FYI - There are some logical errors in both your shuffle() code and the test. I won't address those here; hopefully having a good test will allow you to figure out the problems!
Writing tests around Random data is hard.
The best option is to pass in an instance of Random to your shuffle() method or it's containing class. Then in test usages, you can pass in an instance of Random which has been seeded with a known value. Given that the Random code will behave the same every time and you control the input array, your test will be deterministic; you can confidently assert on each object in the sorted collection.
The only downside of this approach is that you won't have a test preventing you from re-writing your shuffle() method to simply re-order the elements every time into this specified order. But that might be over-thinking it; usually we can trust our future selves.
An alternative approach is to assume that in a Random world, given enough time, every data possibility will be realized.
I used this approach when testing a 6-sided die's roll() method. I needed to ensure that getting all values from 1-6 was possible. I didn't want to complicate the method signature or the Die constructor to take in an instance of Random. I also didn't feel confident in a test that used a known seed and simply always asserted 3 (i.e.).
Instead, I made the assumption that given enough rolls, all values from 1-6 would eventually be rolled. I wrote a test that infinitely called roll until all values from 1-6 had been returned. Then I added a timeout to the test so that it would fail after 1 second if the above condition hadn't been met.
#Test(timeout = 1000)
public void roll_shouldEventuallyReturnAllNumbersBetweenOneAndSixInclusively() {
Die die = new Die();
Set<Integer> rolledValues = new HashSet<Integer>();
int totalOfUniqueRolls = 0;
while (rolledValues.size() < Die.NUM_SIDES) {
if (rolledValues.add(die.roll())) {
totalOfUniqueRolls += die.getFaceValue();
}
}
assertEquals(summation(1, Die.NUM_SIDES), totalOfUniqueRolls);
}
Worst case scenario it fails after 1 second (which hasn't happened yet) but it usually passes in about 20 milliseconds.
The test must be reproducible: it is not useful if it depends on something random.
I suggest you to use mocking so the CUT (code under test) don't use the real Random class instantiated in production, but a different class written by you with a predictable behavior, giving you the possibility to make some significant assertions on two or three items.
It appears your shuffle() method will always return the same result. So given a input test array of however many elements in your test, just specify the exact output array you'd expect.
It looks like you are trying to write a very general test. Instead, your tests should be very specific: given a specific input A then you expect a specific output B.
I'm working on training myself in a very rigid Test Driven Development JUnit atmosphere. I'm trying to find out what the best method for testing FOR randomness would be in such an atmosphere. For example, I'm working on implementing a randomized queue array that queues and item and immediately switches that item with an item with index 0-(n-1) on the array (thus simulating a random item coming off the queue when it is dequeued). Here's some example code form my enqueue method:
int randIndex = StdRandom.uniform(size); // generate random index to swap with last item
Item tmp = randArray[randIndex];
randArray[size] = item;
randArray[randIndex] = randArray[size]; //perform swap to create a random item for dequeue
randArray[size] = tmp;
size++;
I want to run a few tests to make sure that my enqueue method is actually randomly switching the queued variable with some other index in the array. Normally I'd just throw some code in the Main() method that iterates through a bunch of enqueue() calls and prints the results, then I'd check to make sure it "felt" random.
But, like I said, I want to do this in a very rigid unit testing framework. It seems like JUnit pretty much exclusively uses assert statements, but I'm not sure what I should assert against what, unless I just run some Monte Carlo type thing and check the average against a certain epsilon, but that seems a little much for testing such a simple method.
You can split the test in two parts.
1) You test that by a given sequecne of pseudo random numbers, your queing works as expected. For that define any arbitray fixed number of int values: e.g "5,2,100,3".
Then test with asser that the enque, deque delivers that expected element.
2) Test the Random() class of java: You, most likely should omit that test, because Random() is well implemented.
Otherwise for 2) you have it using Chi-Square Random Number Test, and that that that thi sstatistic is within soem epsilon as you stated. But this woul dbe an overkill, so stay with point 1)
I'm not sure what you are really heading for but I read it like testing the random number generator itself (cause your switching is .. quite straight forward).
If you use java SecureRandom, you should be on a quite good side regarding the entropy, see
SecureRandom. If you doubt that, use some entropy checkers or just a sequence of real random from some source in the internet like here
I am working to create a crawler- a java web app, in which users can define crawl jobs, which extract and store information from specific websites.
As part of this work, there is a 'loop' construct... it has a list portion, which is evaluated initially (and typically represents a list of values)... After that is the loop body, which is executed once for each item in the list (from the list portion mentioned previously).
Note that there can be a loop construct within another loop construct, and so on.
The problem is, sometimes one list can contain millions of rows of data - and the body is to be executed for each row in this list. The body has a start index value, upper bound for the index, and is incremented by one.
What I want to do is, for a single level loop, initially calculate the list value and store it in database. After that, instead of executing the body in one go, split it up into different sections so that different sections of the list are processed in parallel.
However, how do I split up a job for an n-level loop? (Ie one loop within one loop and so on.)
Is there some recommended way of doing such processing... Any tutorial or guide you could point me to, would be very helpful for me.
I suggest packing the processing logic for 1 element of the list into a Runnable or Callable, and then pass them to an Executor for execution. This will run tasks in parallel in different worker-threads. Of course it depends on how many cores your machine has, how "parallel" this will really be.
If each element of the list can be processed completely independent of all the others, than this would be the way to go for me, instead of messing around myself with Threads and dividing the list into sublists etc.
According your description, i got that you are fetching the source code of xyz website and scrap data from that.
You can use XPath and RegularExpression to do this kind of task as its best. use JSOUP for that ,it helps you a lot.
As far as parallelization is concern you can use the .select , getElementbyId, getElementByClass of JSOUP (it's a opensource). than simply put a
for(i=0 ;i< length;i++)
{
i am fetching i;
i am fetching i+1;
int temp=i+1;
if(temp>=length)
{
break;
}
}
hope this helps: http://jsoup.org
This sounds like a great candidate for the Java 7 fork / join framework
Lets say you create 3 thread: T1, T2, T3. and following is the looping construct, for eaxmple
for(int i=0; i<100; i++)
{
for(int j=0; j<100; j++)
{
for(int k=0; k<100; k++)
{
// do some processing.
}
}
}
Modify the increment part as i += no. of threads. In this case it will be i += 3
Thus, the initial values of i, j, k will vary for each thread.
For T1: i = 0;
For T2: i = 1;
For T3: i = 2;
Similary the loop limit can be set.