My test part is the following:
#Test
//testing user report method of UserAdmin - number of users less than 10
public void testuserReport_SizeLessThan10() throws Exception
{
new Expectations() {{
dBConnection.getUsers();
times=1;
result= Arrays.asList("Abc","123");
}};
System.out.println("in less than 10");
userAdmin.runUserReport();
}
The method under test belonging to a class named userAdmin is the following:
public void runUserReport() {
try {
List<User> users = dbConn.getUsers();
System.out.println(users.size());
if (users.isEmpty()) { // empty database
System.out.println("No users in database...");
} else if (users.size() <= 10) { // detailed reporting
System.out.println("Listing all usernames:");
for (User user : users) {
System.out.println(user.getUsername());
}
} else { // summary reporting
System.out.println("Total number of users: " + users.size());
System.out.println(users.get(0).getUsername());
System.out.println(users.get(1).getUsername());
System.out.println(users.get(2).getUsername());
System.out.println(users.get(3).getUsername());
System.out.println(users.get(4).getUsername());
System.out.println((users.size() - 5) + " more...");
}
} catch (SQLException sqle) {
System.out.println("DBConnection problem at runUserReport().");
}
}
My tests runs by giving the size of users as 2 but it does not print the usernames starting with "Listing all usernames:" as defined in the method. Am i defining the result wrongly in the expectations part of the test? Please help
I am not even sure how come System.out.println(users.size()); prints the size as 2 and not the test fails.
List<User> users = dbConn.getUsers(); says that users is a List of User type while result= Arrays.asList("Abc","123"); makes result as List of String, List<String>. You are assigning List<String> to List<User> and somehow it doesn't fail at run time.
You need to prepare a List of User type and assign to result instead of what you are doing currently.
Related
I am automating e-commerce website. I am using JUNIT-Selenium framework.
Their are two files i am working with, first is the "TestCase.java" where my test steps are mentioned, aslo to start automation i run this file and second file is "TestMain.java" which has validation methods which will used by First file to verify and input the data in UI (mostly using If ..else validation).
First file consist of Automation initiation code, which uses Hashmap for reading the excel, extent report initiation and flush and use methods from testMain.java for input of data and validation through if... else statement.
TestCase.java looks like this:
public class TestCase extends AppTest {
private StringBuffer verificationErrors = new StringBuffer();
#Override
#Before
public void setUp() throws Exception {
super.setUp();
preparation = new Prep();
application = new AppToTest();
user = new Environment();
}
#Test
public void testLAP_Creamix() throws Exception {
try {
launchMainApplication();
Test_frMain Test_frMainPage = new Test_frMain(tool, test, user, application);
HashMap<String, ArrayList<String>> win = CreamixWindowsDataset.main();
SortedSet<String> keys = new TreeSet<>(win.keySet());
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("Test_Report.html");
ExtentReports extent = new ExtentReports();
extent.attachReporter(htmlReporter);
ExtentTest test1 = extent.createTest("Creamix test");
for (String i : keys) {
System.out.println("########### Test = " + win.get(i).get(0) + " ###########");
Lapeyre_frMainPage.EnterTaille(win.get(i).get(1));
Lapeyre_frMainPage.SelectCONFIGURATION(win.get(i).get(2));
Lapeyre_frMainPage.SelectPLANVASQUE(win.get(i).get(3));
Lapeyre_frMainPage.SelectCOULEUR(win.get(i).get(4));
Lapeyre_frMainPage.SelectPOIGNEES(win.get(i).get(5));
Lapeyre_frMainPage.SelectTYPE_DE_MEUBLE(win.get(i).get(6));
Lapeyre_frMainPage.SelectCHOISISSEZ(win.get(i).get(7));
Lapeyre_frMainPage.VerifyREFERENCE(win.get(i).get(8));(FROM HERE Validation Starts)
Lapeyre_frMainPage.VerifyQUANTITY(win.get(i).get(9));
Lapeyre_frMainPage.VerifyREFERENCETwo(win.get(i).get(10));
Lapeyre_frMainPage.VerifyQUANTITYTwo(win.get(i).get(11));
Lapeyre_frMainPage.VerifyREFERENCEThree(win.get(i).get(12));
Lapeyre_frMainPage.VerifyQUANTITYThree(win.get(i).get(13));
Lapeyre_frMainPage.VerifyREFERENCEFour(win.get(i).get(14));
Lapeyre_frMainPage.VerifyQUANTITYFour(win.get(i).get(15));
Lapeyre_frMainPage.VerifyREFERENCEFive(win.get(i).get(16));
Lapeyre_frMainPage.VerifyQUANTITYFive(win.get(i).get(17));
Lapeyre_frMainPage.VerifyREFERENCESix(win.get(i).get(18));
Lapeyre_frMainPage.VerifyQUANTITYSix(win.get(i).get(19));
Lapeyre_frMainPage.VerifyREFERENCESeven(win.get(i).get(20));
Lapeyre_frMainPage.VerifyQUANTITYSeven(win.get(i).get(21));
Lapeyre_frMainPage.VerifyPanierPrice(win.get(i).get(22));
Lapeyre_frMainPage.VerifyECO_PARTPrice(win.get(i).get(23));
Lapeyre_frMainPage.ClickCREAMIXReinit();(Reset button to test next scenario)
test1.pass("Scenario " + win.get(i).get(0) + " is passed");
System.out.println("########### Test End ##############");
extent.flush();----------(Extent report over)
}
test.setResult("pass");
} catch (AlreadyRunException e) {
} catch (Exception e) {
verificationErrors.append(e.getMessage());
throw e;
}
}
#Override
#After
public void tearDown() throws Exception {
super.tearDown();
}
}
(Please note one loop is one scenario where im customizing and validating price of the product and then clicking reset button to next scenario for doing same)
And,
"TestMain.java" from where i am using methods to validate
one of the method is shown below
public void VerifyREFERENCE(String REF_1) throws Exception {
System.out.println("Verifying reference article");
if (REF_1.equals("SKIP")) {
System.out.println("SKIPPED");
} else {
WebElement referenceOne = tool.searchUsingXPath("//tbody//tr[1]//td//div[2]");
String Ref1 = referenceOne.getText().trim();
System.out.println("ref 1 is " + Ref1);
if (Ref1.equals("Ref. de l'article : " + REF_1)) {
System.out.println("Reference 1 is correct");
} else {
System.out.println("Reference 1 is incorrect");
}
}
}
I am using extent report in TestCase.java(Please check above code) to report my scenarios, but the problem is It shows all test case as PASS and if any failure occurs it doesn't report(it terminates).
Reason being i have not used assertions anywhere, BUT HOW CAN I APPLY SUCH ASSERTIONS IN THIS FRAMEWORK
TO SUMMARIZE:
1- I need to add price validation check in report
2- i tried of using this line in TestCase.java "assertEquals("Verify REFERENCE 1", win.get(i).get(8), Lapeyre_frMainPage.GetREFERENCE());" but i cant use assertion in TestCase.java(it wont allow me).
3- Please show me alternative way to report PASS and FAIL for such frameworks, where in extent report i can able to show price mismatch between excel and UI.
You can only expect assertEquals() to work if your TestCase class extends junit test, or if you implement the method yourself in your code.
In any case, you seem to be trying to use ExtentReports. I am not experienced with that library, but according to the javadoc for ExtentTest, it appears that you are expected to call .pass() or .fail() yourself based on the outcome of your test.
In your TestCase, I believe you want to try to maintain a boolean to track if the test has passed or not.
The first step would be to modify VerifyREFERENCE() to return a boolean indicating if it passed or failed, instead of being void.
public boolean VerifyREFERENCE(String REF_1) throws Exception {
System.out.println("Verifying reference article");
if (REF_1.equals("SKIP")) {
System.out.println("SKIPPED");
} else {
WebElement referenceOne = tool.searchUsingXPath("//tbody//tr[1]//td//div[2]");
String Ref1 = referenceOne.getText().trim();
System.out.println("ref 1 is " + Ref1);
if (Ref1.equals("Ref. de l'article : " + REF_1)) {
System.out.println("Reference 1 is correct");
return true;
} else {
System.out.println("Reference 1 is incorrect");
return false;
}
}
}
Then, in your TestCase, initialise a boolean to true just before the loop. Inside the loop, perform a logical AND (&&) with the return value of each VerifyREFERENCE() call. Finally, after the loop finishes, test the value of the boolean, and pass or fail the ExtentTest as appropriate:
ExtentTest test1 = extent.createTest("Creamix test");
boolean passed = true;
for (String i : keys) {
System.out.println("########### Test = " + win.get(i).get(0) + " ###########");
Lapeyre_frMainPage.EnterTaille(win.get(i).get(1));
....
Lapeyre_frMainPage.SelectCHOISISSEZ(win.get(i).get(7));
passed = passed && Lapeyre_frMainPage.VerifyREFERENCE(win.get(i).get(8));(FROM HERE Validation Starts)
passed = passed && Lapeyre_frMainPage.VerifyQUANTITY(win.get(i).get(9));
...
passed = passed && Lapeyre_frMainPage.VerifyECO_PARTPrice(win.get(i).get(23));
Lapeyre_frMainPage.ClickCREAMIXReinit();(Reset button to test next scenario)
if(passed) {
test1.pass("Scenario " + win.get(i).get(0) + " is passed");
} else {
test1.fail("Scenario " + win.get(i).get(0) + " is failed");
}
System.out.println("########### Test End ##############");
extent.flush();----------(Extent report over)
}
I am evaluating the AppEngine Document Indexes Fulltext Search, and run into some problems while using the Stem Operator '~'.
Basically I created an index of a few test documents, all with a title field. Some of the example values of the field are:
"Houses Desks Tables"
"referer image vod event"
"events with cats and dogs and"
"names very interesting days"
I'm using Java, and a snippet of my query code looks like below:
Document doc = Document.newBuilder().setId(key)
.addField(Field.newBuilder().setName("title").setText(title))
.addField(Field.newBuilder().setName("type").setText(type))
.addField(Field.newBuilder().setName("username").setText(username))
.build();
DocumentSearchIndexService.getInstance().indexDocument(indexName, doc);
IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build();
Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
return index.search("title = ~"+searchText);
However, the returned result will always only matching the exact singular or plural form:
query cat, return nothing
query dog, return nothing
query name, return nothing
query house, return nothing
query cats, return "events with cats and dogs and"
query dogs, return "events with cats and dogs and"
query names, return "names very interesting days"
query houses, return "Houses Desks Tables"
So I am really lost as in how the entries are returned, or if the way my query constructed is not correct.
Notice that stemming is not implemented if you are using the Java Development Server for Java 8 on the Standard Environment.
If you are deploying your application on App Engine use the Utils.java class found here to properly index your document.
I cloned the repository for the java-docs-samples for Google Cloud Platform, went to the appengine-java8/search folder and modified the code for the SearchServlet.java class in the following way in order to include queries with the stem operator "~":
...
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
Document doc =
Document.newBuilder()
.setId("theOnlyPiano")
.addField(Field.newBuilder().setName("product").setText("cats and dogs"))
.addField(Field.newBuilder().setName("maker").setText("Yamaha"))
.addField(Field.newBuilder().setName("price").setNumber(4000))
.build();
try {
Utils.indexADocument(SEARCH_INDEX, doc);
} catch (InterruptedException e) {
// ignore
}
// [START search_document]
final int maxRetry = 3;
int attempts = 0;
int delay = 2;
while (true) {
try {
String searchText = "cat";
String queryString = "product = ~"+searchText;
Results<ScoredDocument> results = getIndex().search(queryString);
// Iterate over the documents in the results
for (ScoredDocument document : results) {
// handle results
out.print("product: " + document.getOnlyField("product").getText());
//out.println(", price: " + document.getOnlyField("price").getNumber());
}
} catch (SearchException e) {
if (StatusCode.TRANSIENT_ERROR.equals(e.getOperationResult().getCode())
&& ++attempts < maxRetry) {
// retry
try {
Thread.sleep(delay * 1000);
} catch (InterruptedException e1) {
// ignore
}
delay *= 2; // easy exponential backoff
continue;
} else {
throw e;
}
}
break;
}
// [END search_document]
// We don't test the search result below, but we're fine if it runs without errors.
out.println(" Search performed");
Index index = getIndex();
// [START simple_search_1]
index.search("rose water");
// [END simple_search_1]
// [START simple_search_2]
index.search("1776-07-04");
// [END simple_search_2]
// [START simple_search_3]
// search for documents with pianos that cost less than $5000
index.search("product = ~cat AND price < 5000");
// [END simple_search_3]
}
}
and I was able to verify that the stem operator works "~" correctly for plurals (with words like cats, dogs, etc.). But notice that as mentioned on the documentation the stemming algorithm has its limitations.
Note. If you want to replicate the steps I made don't forget to comment the testing section on the SearchServletTest.java class prior deploying the application to App Engine with mvn appengine:deploy. The file should look like this:
...
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void doGet_successfulyInvoked() throws Exception {
// servletUnderTest.doGet(mockRequest, mockResponse);
// String content = responseWriter.toString();
// assertWithMessage("SearchServlet response").that(content).contains("maker: Yamaha");
// assertWithMessage("SearchServlet response").that(content).contains("price: 4000.0");
}
}
I am using an example of recently released Google's People API from here. I have extended a sample a bit to display additional information about the contact such as an email address and a phone number. The code that should do the job is presented below.
public class PeopleQuickstart {
...
public static void getPersonInfo(Person person){
// Get names
List<Name> names = person.getNames();
if(names != null && names.size() > 0) {
for(Name personName: names) {
System.out.println("Name: " + personName.getDisplayName());
}
}
// Get email addresses
List<EmailAddress> emails = person.getEmailAddresses();
if(emails != null && emails.size() > 0) {
for(EmailAddress personEmail: emails) {
System.out.println("Email: " + personEmail.getValue());
}
}
// Get phone numbers
List<PhoneNumber> phones = person.getPhoneNumbers();
if(phones != null && phones.size() > 0) {
for(PhoneNumber personPhone: phones){
System.out.println("Phone number: " + personPhone.getValue());
}
}
}
public static void main(String [] args) throws IOException {
People service = getPeopleService();
// Request 120 connections.
ListConnectionsResponse response = service.people().connections()
.list("people/me")
.setPageSize(120)
.execute();
// Display information about your connections.
List<Person> connections = response.getConnections();
if (connections != null && connections.size() > 0) {
for (Person person: connections){
getPersonInfo(person);
}
} else {
System.out.println("No connections found.");
}
}
}
I am testing this program with my contact list and I can successfully obtain a list of people along with the name fields. However, I cannot get values for email addresses and phone numbers (lists are always null), although I do have these values set in my contact list (verified through Gmail->Contacts). What am I missing?
Ok, problem solved. It looks like Google's documentation is a bit misleading (well, it has just been released;)). When I try to fetch my contacts using people.connections.list (see here) there are several query parameters that can be set. However, for the requestMask parameter it is stated that "Omitting this field will include all fields" which is not the case (at least did not work for me). Therefore, one has to explicitly specify which fields to be returned in the response. The modified code is given below. I wish Google people would clarify this point a bit.
public class PeopleQuickstart {
...
public static void main(String [] args) throws IOException {
People service = getPeopleService();
// Request 120 connections.
ListConnectionsResponse response = service.people().connections()
.list("people/me")
.setPageSize(120)
// specify fields to be returned
.setRequestMaskIncludeField("person.names,person.emailAddresses,person.phoneNumbers")
.execute();
// Display information about a person.
List<Person> connections = response.getConnections();
if (connections != null && connections.size() > 0) {
for (Person person: connections){
getPersonInfo(person);
}
} else {
System.out.println("No connections found.");
}
}
}
I want all the list of tweets which are favorited by a twitter user account.
I have done some sample code that will give me all the posts that the user posted but i want all the tweets that the user favorited.
public List getAllTweetsOfUser(Twitter twitter, String user) {
if (user != null && !user.trim().isEmpty()) {
List statuses = new ArrayList();
int pageno = 1;
while (true) {
try {
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(user, page));
if (statuses.size() == size) {
break;
}
} catch (TwitterException e) {
}
}
return statuses;
} else {
return null;
}
}
Can any one help me in this..
You need to start the paging with 1, and then increment the page. However, note that you will be rate limited, if you exceed 15 requests per 15 minutes (or 15* 20 = 300 statuses per 15 minutes).
Paging paging = new Paging(1);
List<Status> list;
do{
list = twitter.getFavorites(userID, paging);
for (Status s : list) {
//do stuff with s
System.out.println(s.getText());
}
paging.setPage(paging.getPage() + 1);
}while(list.size() > 0);
One of the Twitter4J samples does exactly this.
public final class GetFavorites {
/**
* Usage: java twitter4j.examples.favorite.GetFavorites
*
* #param args message
*/
public static void main(String[] args) {
try {
Twitter twitter = new TwitterFactory().getInstance();
List<Status> statuses = twitter.getFavorites();
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
System.out.println("done.");
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get favorites: " + te.getMessage());
System.exit(-1);
}
}
}
I have tried like below..
ResponseList<Status> status = twitter.getFavorites(twitterScreenName);
It given me the favorite tweets of the user which i have passed as a parameter. But the problem here is i am able to get only 20 favorites, though the user has so many tweets.
ResponseList<Status> status = twitter.getFavorites(twitterScreenName, paging);
I tried with the paging but i am not sure how to use this paging. So i am getting the top 20 favorites using my first code. If anybody tried this then please share the info like how to get all favorites of a given user.
This is a very basic problem, but I cannot seem to solve/figure out the problem so hoping some fresh eyes can help out.
I have a model User which has username and password. I want to allow Users to update their password, so I added update() method as shown below:
public static void update(User user) throws UserException {
User record = User.getById(user.id);
if (null == record) {
throw new UserException(BaseException.invalidRecordMessageException(User.class.getSimpleName()));
}
if (!StringUtils.equals(record.username, user.username)) {
throw new UserException(BaseException.unmodifiableFieldMessageException(User.class.getSimpleName(), "username"));
}
validatePassword(user.password);
saveUser(user);
}
And here is my saveUser():
private static void saveUser(User user) {
user.password = encryptPassword(user.password);
user.save();
System.out.println("n: " + user.id);
System.out.println("n: " + user.username);
System.out.println("n: " + user.password);
User r = User.getById(user.id);
System.out.println("r: " + r.id);
System.out.println("r: " + r.username);
System.out.println("r: " + r.password);
}
I added a test to confirm that the functionality is working perfectly.
#Test
public void testUpdateUserPasswordWithValidPasswordShouldUpdateRecord() {
try {
User dummy = new User(DEFAULT_USERNAME, DEFAULT_RAW_PASSWORD);
User.create(dummy);
assertNotNull(dummy.id);
User record = User.getById(dummy.id);
assertEquals(DEFAULT_USERNAME, record.username);
assertEquals(DEFAULT_RAW_PASSWORD, record.password);
dummy.password = DEFAULT_RAW_PASSWORD + "_extra";
User.update(dummy);
User updatedRecord = User.getById(dummy.id);
assertEquals(dummy.username, updatedRecord.username);
assertEquals(dummy.password, updatedRecord.password);
} catch (UserException ue) {
fail("Test should not throw exception.");
}
}
However, the test is failing as the record does not seem to be updating:
Test UserTest.testUpdateUserPasswordWithValidPasswordShouldUpdateRecord failed: expected:<$uP3rsecretpassword[_extra]> but was:<$uP3rsecretpassword[]>
DEFAULT_PASSWORD = $uP3rsecretpassword
Here is the output of all System.out.println() calls:
--- initial create ---
n: 1
n: moo
n: $uP3rsecretpassword
r: 1
r: moo
r: $uP3rsecretpassword
--- update ---
n: 1
n: moo
n: $uP3rsecretpassword_extra
r: 1
r: moo
r: $uP3rsecretpassword
Thanks in advance to any help.
I believe the problem lies in this line:
User record = User.getById(user.id);
Hibernate only keeps around one object of a certain id. So, here, you're effectively overwriting the change which is contained in the object user with the (old) state currently in the DB.
As for the checks you're doing there, they seem to be a bit superfluous anyways as you're not trusting your own code.