Java Unit Testing Help for loop - java

public void login(String username, String password) {
for(int i = 0; i < Users.size(); i++) {
user users = (user) Users.get(i);
if(users.getUsername().contains(username)
&& users.getPassword().contains(password)) {
userName = users.getUsername();
userLevel = users.getUserLevel();
isSuccess = true;
}
}
}
Hello everyone. I'm trying to do a java unit testing for this method using Java Junit. But i don't know how to do that? Because there's a for loop.
Let me explain the method.
for(int i=0;i<Users.size();i++){
This "Users" is a vector. This loop runs unit this vector ends.
user users = (user) Users.get(i);
Then im calling user class for user instance.
if((users.getUsername().contains(username)) &&
(users.getPassword().contains(password))) {
Then if any of the users that matches with the values in the vectors, this gives the output.
Can anyone tell me how to write a unit test for this?

Your code is hard to read. Learn Java coding standards.
Your method should not be printing anything. Determine if the user is valid. Print messages elsewhere.
I'll assume you've got a class User that encapsulates credentials:
package misc.user;
import org.apache.commons.lang3.StringUtils;
/**
* Created by Michael
* Creation date 8/5/2017.
* #link https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop
*/
public class User {
private final String username;
private final String password;
public User(String username, String password) {
if (StringUtils.isBlank(username)) throw new IllegalArgumentException("username cannot be blank or null");
if (StringUtils.isBlank(password)) throw new IllegalArgumentException("password cannot be blank or null");
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
User user = (User) o;
if (!getUsername().equals(user.getUsername())) { return false; }
return getPassword().equals(user.getPassword());
}
#Override
public int hashCode() {
int result = getUsername().hashCode();
result = 31 * result + getPassword().hashCode();
return result;
}
#Override
public String toString() {
return "{\"User\":{"
+ "\"username\":\"" + username + "\""
+ ",\"password\":\"" + password + "\""
+ "}}";
}
}
I'd test it using JUnit:
package misc.user;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael
* Creation date 8/5/2017.
* #link https://stackoverflow.com/questions/45524768/java-unit-testing-help-for-loop
*/
public class UserTest {
private static List<User> users;
#BeforeClass
public static void setUp() {
users = new ArrayList<>();
users.add(new User("FooBar", "myPassword"));
users.add(new User("GeorgeBush", "exPrez"));
users.add(new User("weatherBoy", "cloudy"));
}
#Test
public void testLogin_Success() {
// setup
String username = "weatherBoy";
String password = "cloudy";
// exercise
boolean isValidUser = users.contains(new User(username, password));
// assert
Assert.assertTrue(isValidUser);
}
#Test
public void testLogin_Failure() {
// setup
String username = "noSuchUser";
String password = "does not matter";
// exercise
boolean isValidUser = users.contains(new User(username, password));
// assert
Assert.assertFalse(isValidUser);
}
}

Related

Trying to figure out unexplained error with JUnit tests and model object

I am working on modeling several java objects that manage entities in a mySQL database using the JDBCTemplate.
I have run Add/Get JUnit tests on two other objects and I am not getting any errors, but I cannot figure out what is causing this error for my 'Organization' object.
Here is my 'Organization' dto code:
package com.sg.superherosightings.model;
import java.util.Objects;
public class Organization {
private int orgId;
private String orgName;
private String orgDescription;
private String orgPhone;
private String orgEmail;
private String orgStreetAddress;
private String orgCity;
private String orgState;
private String orgZipCode;
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getOrgDescription() {
return orgDescription;
}
public void setOrgDescription(String orgDescription) {
this.orgDescription = orgDescription;
}
public String getOrgPhone() {
return orgPhone;
}
public void setOrgPhone(String orgPhone) {
this.orgPhone = orgPhone;
}
public String getOrgEmail() {
return orgEmail;
}
public void setOrgEmail(String orgEmail) {
this.orgEmail = orgEmail;
}
public String getOrgStreetAddress() {
return orgStreetAddress;
}
public void setOrgStreetAddress(String orgStreetAddress) {
this.orgStreetAddress = orgStreetAddress;
}
public String getOrgCity() {
return orgCity;
}
public void setOrgCity(String orgCity) {
this.orgCity = orgCity;
}
public String getOrgState() {
return orgState;
}
public void setOrgState(String orgState) {
this.orgState = orgState;
}
public String getOrgZipCode() {
return orgZipCode;
}
public void setOrgZipCode(String orgZipCode) {
this.orgZipCode = orgZipCode;
}
#Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + this.orgId;
hash = 89 * hash + Objects.hashCode(this.orgName);
hash = 89 * hash + Objects.hashCode(this.orgDescription);
hash = 89 * hash + Objects.hashCode(this.orgPhone);
hash = 89 * hash + Objects.hashCode(this.orgEmail);
hash = 89 * hash + Objects.hashCode(this.orgStreetAddress);
hash = 89 * hash + Objects.hashCode(this.orgCity);
hash = 89 * hash + Objects.hashCode(this.orgState);
hash = 89 * hash + Objects.hashCode(this.orgZipCode);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Organization other = (Organization) obj;
if (this.orgId != other.orgId) {
return false;
}
if (!Objects.equals(this.orgName, other.orgName)) {
return false;
}
if (!Objects.equals(this.orgDescription, other.orgDescription)) {
return false;
}
if (!Objects.equals(this.orgPhone, other.orgPhone)) {
return false;
}
if (!Objects.equals(this.orgEmail, other.orgEmail)) {
return false;
}
if (!Objects.equals(this.orgStreetAddress, other.orgStreetAddress)) {
return false;
}
if (!Objects.equals(this.orgCity, other.orgCity)) {
return false;
}
if (!Objects.equals(this.orgState, other.orgState)) {
return false;
}
if (!Objects.equals(this.orgZipCode, other.orgZipCode)) {
return false;
}
return true;
}
}
Here is my Mapper Method in my DaoDBImpl:
img of OrgMapper Method before fix
This is my SuperSightings_DaoTest method causing the error:
package com.sg.superherosightings.dao;
import com.sg.superherosightings.model.Location;
import com.sg.superherosightings.model.Organization;
import com.sg.superherosightings.model.Power;
import com.sg.superherosightings.model.Sighting;
import com.sg.superherosightings.model.Supe;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SuperSightings_DaoTest {
SuperSightings_Dao dao;
public SuperSightings_DaoTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
ApplicationContext ctx
= new ClassPathXmlApplicationContext("test-applicationContext.xml");
dao = ctx.getBean("SuperSightings_Dao", SuperSightings_Dao.class);
// delete all supes
List<Supe> supes = dao.getAllSupes(); for (Supe currentSupe : supes) {
dao.deleteSupe(currentSupe.getSupeId());
}
// delete all powers
List<Power> powers = dao.getAllPowers(); for (Power currentPower : powers) {
dao.deletePower(currentPower.getPowerId());
}
//delete all organizations
List<Organization> orgs = dao.getAllOrganizations(); for (Organization currentOrg : orgs) {
dao.deleteOrganization(currentOrg.getOrgId());
}
// delete all locations
List<Location> locations = dao.getAllLocations(); for (Location currentLocation : locations) {
dao.deleteLocation(currentLocation.getLocationId());
}
// delete all sightings
List<Sighting> sightings = dao.getAllSightings(); for (Sighting currentSighting : sightings) {
dao.deleteSighting(currentSighting.getSightingId());
}
}
#After
public void tearDown() {
}
/**
* Test of addPower method, of class SuperSightings_Dao.
*/
#Test
public void testAddGetPower() {
Power power = new Power();
power.setPowerType("Fire");
power.setPowerDescription("Shoots fire from hands");
dao.addPower(power);
Power fromDao = dao.getPowerById(power.getPowerId());
assertEquals(fromDao, power);
}
/**
* Test of deletePower method, of class SuperSightings_Dao.
*/
#Test
public void testDeletePower() {
Power power = new Power();
power.setPowerType("Fire");
power.setPowerDescription("Shoots fire from hands");
dao.addPower(power);
Power fromDao = dao.getPowerById(power.getPowerId());
assertEquals(fromDao, power);
dao.deletePower(power.getPowerId());
assertNull(dao.getPowerById(power.getPowerId()));
}
/**
* Test of getAllPowersBySupeId method, of class SuperSightings_Dao.
*/
#Test
public void testGetAllPowersBySupeId() {
}
/**
* Test of addOrganization method, of class SuperSightings_Dao.
*/
#Test
public void testAddGetOrganization() {
Organization org = new Organization();
org.setOrgName("Legion of Doom");
org.setOrgDescription("evil organization");
org.setOrgPhone("333-444-5678");
org.setOrgEmail("lod#evil.org");
org.setOrgStreetAddress("344 Lowland Blvd.");
org.setOrgCity("Quahog");
org.setOrgState("RI");
org.setOrgZipCode("09678");
dao.addOrganization(org);
Organization fromDao = dao.getOrganizationById(org.getOrgId());
assertEquals(fromDao, org); //this is the line causing the error
}
This is the error I am getting:
testAddGetOrganization(com.sg.superherosightings.dao.SuperSightings_DaoTest)
Time elapsed: 0.107 sec <<< FAILURE! java.lang.AssertionError:
expected:com.sg.superherosightings.model.Organization#ae511546 but
was:com.sg.superherosightings.model.Organization#15fabf0f
Please let me know if I need to provide further information. i am trying to get better at how i post questions here. I searched for a long time before asking but all I can find is that it might be something with my equals/hash code. I'm just not sure what is getting changed when the comparison is made because it is not happening with my other objects.
Thank you for any hints, and please don't bite my head off!
It seems some fields are not equal. try to compare all fields one by one to identify non-equal fields: assertEquals(fromDao.getOrgId(), org.getOrgId() and all the rest of organization's fields)
Thank you all for your assistance! I was able to convert my org and fromDao objects to string to see them in the test window. The problem was with my Mapper method for the Organization object. See original and the fix below:
Original Version
private static final class OrgMapper implements RowMapper<Organization> {
#Override
public Organization mapRow(ResultSet rs, int i) throws SQLException {
Organization org = new Organization();
org.setOrgId(rs.getInt("org_id"));
org.setOrgName(rs.getString("org_name"));
org.setOrgDescription(rs.getString("org_description"));
org.setOrgPhone(rs.getString("org_phone"));
org.setOrgEmail(rs.getString("org_street_address")); //wrong field
org.setOrgCity(rs.getString("org_city"));
org.setOrgState(rs.getString("org_state"));
org.setOrgZipCode(rs.getString("org_zip_code"));
return org;
}
}
Fixed OrgMapper:
private static final class OrgMapper implements RowMapper<Organization> {
#Override
public Organization mapRow(ResultSet rs, int i) throws SQLException {
Organization org = new Organization();
org.setOrgId(rs.getInt("org_id"));
org.setOrgName(rs.getString("org_name"));
org.setOrgDescription(rs.getString("org_description"));
org.setOrgPhone(rs.getString("org_phone"));
org.setOrgEmail(rs.getString("org_email"));
org.setOrgStreetAddress(rs.getString("org_street_address"));
org.setOrgCity(rs.getString("org_city"));
org.setOrgState(rs.getString("org_state"));
org.setOrgZipCode(rs.getString("org_zip_code"));
return org;
}

How to check requested GraphQL fields in Java with fragments?

I have a GraphQL query similar to this:
query {
getPosts {
...PostFragment
}
}
fragment SpecificPostFragment on SpecificPost {
owner {
id
name
}
}
fragment PostFragment on Post {
id
object
... on SpecificPost {
...SpecificPostFragment
}
}
I try to know if:
the field object is requested
the field owner is requested
I try to apply what is written here:
https://www.graphql-java.com/documentation/v11/fieldselection/
But dataFetchingEnvironment.getSelectionSet().contains("XXX") does not seem to work well with fragments.
How to do that ?
I haven't found any built-in solution, so I wrote my own. Here is my code
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import graphql.execution.MergedField;
import graphql.language.Field;
import graphql.language.FragmentDefinition;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.SelectionSet;
import graphql.schema.DataFetchingEnvironment;
public class GraphQLUtil {
private static class PathElement {
private final String name;
private final String typeName;
public PathElement(String name, String typeName) {
this.name = name;
this.typeName = typeName;
}
public String getName() {
return name;
}
public String getTypeName() {
return typeName;
}
}
public static boolean containsIncludingFragments(DataFetchingEnvironment env, String path) {
Objects.requireNonNull(env, "The data fetching environment must not be null");
Objects.requireNonNull(path, "The field path must not be null");
List<PathElement> elts = Stream.of(path.split("/")).map(p -> {
String pt = p.trim();
if (pt.isEmpty()) {
throw new IllegalArgumentException("Empty path element found");
}
int sepIdx = pt.indexOf(":");
String name = pt;
String typeName = null;
if (sepIdx >= 0) {
typeName = pt.substring(0, sepIdx);
name = pt.substring(sepIdx + 1, pt.length());
}
return new PathElement(name, typeName);
}).collect(Collectors.toList());
if (elts.isEmpty()) {
return false;
}
MergedField mf = env.getMergedField();
return searchPathElement(env, elts, 0, mf.getSingleField().getSelectionSet(), null);
}
private static boolean searchPathElement(
DataFetchingEnvironment env,
List<PathElement> elts,
int eltIndex,
SelectionSet selectionSet,
String selectionTypeName) {
if (eltIndex >= elts.size()) {
return true;
}
PathElement currentElt = elts.get(eltIndex);
String currentName = currentElt.getName();
String currentTypeName = currentElt.getTypeName();
List<Field> fields = selectionSet.getSelectionsOfType(Field.class);
boolean found = false;
for (Field f : fields) {
if (f.getName().equals(currentName) && (currentTypeName == null
|| selectionTypeName == null
|| currentTypeName.equals(selectionTypeName))) {
found = searchPathElement(env, elts, eltIndex + 1, f.getSelectionSet(), null);
if (found) {
return true;
}
}
}
List<FragmentSpread> fragments = selectionSet.getSelectionsOfType(FragmentSpread.class);
for (FragmentSpread f : fragments) {
FragmentDefinition fDef = env.getFragmentsByName().get(f.getName());
found = searchPathElement(env, elts, eltIndex, fDef.getSelectionSet(), fDef.getTypeCondition().getName());
if (found) {
return true;
}
}
List<InlineFragment> inlineFragments = selectionSet.getSelectionsOfType(InlineFragment.class);
for (InlineFragment f : inlineFragments) {
found = searchPathElement(env, elts, eltIndex, f.getSelectionSet(), f.getTypeCondition().getName());
if (found) {
return true;
}
}
return false;
}
}
And you call it like this:
DataFetchingEnvironment dataEnv = ... // If like me you use GraphQL SPQR, you can get it with io.leangen.graphql.execution.ResolutionEnvironment
boolean t1= GraphQLUtil.containsIncludingFragments(dataEnv, "id");
boolean t2 = GraphQLUtil.containsIncludingFragments(dataEnv, "owner/id");
boolean t3 = GraphQLUtil.containsIncludingFragments(dataEnv, "SpecificPost:owner/id"); // You may give the type of the field, if in some inheritance scenario, it is ambiguous
Note that this solution does not support wild card (* or ?). And I haven't tested it if the main query contains multiple entries (getPost + getPeople in the same query for example), but that probably does not work in that case.

why the getter method goes null when i call in another class?

but in the set method on another class when i got the value is exist,,
so i have 3 classes the first class is getter setter class , second is the class to fill the set and the last is class to get the method getter,, but it goes null value...
public class loginAdminn {
String Username, Password;
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
}
// method to fill the set on another class
public void in(){
loginAdminn p = new loginAdminn();
String user = Username.getText();
String pass = Password.getPassword().toString();
p.setUsername(user);
p.setPassword(pass);
// new NewMain().run();
tes.jalankan();
}
// class method getter (null)
public void jalankan() {
loginAdminn br = new loginAdminn();
String kueri = "Select Username, password from Admin";
int x = 0;
try {
ps = conn.prepareStatement(kueri);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (br.getUsername().equalsIgnoreCase(rs.getString("Username"))) {
if (br.getPassword().equalsIgnoreCase(rs.getString("Password"))) {
JOptionPane.showMessageDialog(null, "Masuk Berhasil");
x = 1;
break;
}
}
}
if (x == 1) {
HomeAdmin b = new HomeAdmin();
b.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Masuk Gagal");
DaftarAplikasi da = new DaftarAplikasi();
da.setVisible(true);
}
ps.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
//the getUsername and getPassword goes null
Class A
String x;
setter getter x
A c = new A();
c.get... // object Class A type X
Class B
A c = new A();
c.get... // object Class B type X
c.get from Class A != c.get from Class B
Basically by using new you're creating two independent from each other objects!
Your getUserName() is coming null because the object you are using to compare has not userName value assigned to it.
public void jalankan() {
//creating an object here , br has no username assigned
loginAdminn br = new loginAdminn();
String kueri = "Select Username, password from Admin";
int x = 0;
try {
ps = conn.prepareStatement(kueri);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if (br.getUsername().equalsIgnoreCase(rs.getString("Username"))) {
if (br.getPassword().equalsIgnoreCase(rs.getString("Password"))) {
JOptionPane.showMessageDialog(null, "Masuk Berhasil");
x = 1;
break;
}
}
}
when you are reading br.getUserName() it is suppose to give you null.

FilteredRowSet is not showing results

I am working on an example using FilteredRowSet, I am trying to run a query, then filter the results using the Predicate object.
Here is my code:
import javax.sql.rowset.FilteredRowSet;
import oracle.jdbc.rowset.OracleFilteredRowSet;
public class Example {
public static void main(String[] args) throws SQLException,
IOException {
try (FilteredRowSet rs = new OracleFilteredRowSet();) {
rs.setUrl("jdbc:oracle:thin:#localhost:1521:xe");
rs.setUsername("dbuser");
rs.setPassword("dbpassword");
rs.setCommand("select * from employees");
rs.execute();
String name[] = {"user1", "user2"};
rs.setFilter(new UserFilter("lastname", name));
while(rs.next()){
String lname= rs.getString("lastName");
System.out.println(lname);
}
}
}
}
Here is my Predicate class:
import javax.sql.RowSet;
import javax.sql.rowset.Predicate;
public class UserFilter implements Predicate {
private String[] names;
private String colName = null;
public UserFilter(String colName, String[] names) {
this.names = names;
this.colName = colName;
}
#Override
public boolean evaluate(RowSet arg0) {
return false;
}
#Override
public boolean evaluate(Object arg0, int arg1) throws SQLException {
return false;
}
#Override
public boolean evaluate(Object valueArg, String colNameArg) throws SQLException {
if (colNameArg.equalsIgnoreCase(this.colName)) {
for (int i = 0; i < this.names.length; i++) {
if (this.names[i].equalsIgnoreCase((String) valueArg)) {
return true;
}
}
}
return false;
}
}
In my database table employees I have records with lastName as values user1 and user2 but when I apply the filter as shown in my question, I am not getting any output. I mean the code is not entering the while loop.
Can you please tell me how to apply the filter? I am expecting the output contains the records whose lastName contains user1 or user2
You have to implement the logic of
public boolean evaluate(RowSet arg0);
As a best practice, your filter should implement the 3 evaluate() methods.
In order to avoid code redundancy in these 3 methods, you can create a private helper method that contains the actual logic of comparing the col/row value with the ones from the filter, and have the 3 evaluate() methods call it. For an example look at this filter, that do not factorise the code logic tough.

How to call a method in the same class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am writing code for an e-mail system and I have one small problem, I can't figure out how to call a method.
what is the correct way to call the writeAllToFile method in the main method?
public class MailboxSystemSol{
public static void main (String args[]) throws IOException{
//code is too long to post here
}
public static void writeAllToFile(Userlist ul, User u, Message me){
//code is too long to post here
}
}
Here is the UserList class:
/**
* Created by Broomhead0 on 4/11/14.
*/
import java.util.ArrayList;
public class Userlist
{
ArrayList<User> users; //this is an arraylist that will store references to all users
public Userlist()
{
users = new ArrayList<User>();
}
// find a user in the list based on the username
public User findUser(String username)
{
// iterate through the array; only iterate according to how many users are currently in the array
for (int i = 0; i < users.size(); i++)
{
// access the particular user through users.(i), then get the name,
// and call the equals method on that name to compare it with the input username
if (users.get(i).userName.equals(username)){
return users.get(i);
}
}
// no user found
return null;
}
// add a user to the list; only do so if the user does not yet exist
public void addUser(User u)
{
if (findUser(u.userName) != null) //if there is a match,
System.out.println("User already exists");
else //if there is not match
{
users.add(u); //add the username
}
}
//check if this is correct
//accessors
public User getUser(int i){
return users.get(i);
}
public int getNumUsers(){
return users.size();
}
}
Here is the User class:
/**
* Created by Broomhead0 on 4/11/14.
*/
public class User
{
public String userName; // the name of the user
public Mailbox outbox; // reference to the mailbox of sent messages
public Mailbox inbox; // reference to the mailbox of received messages
// create mailboxes according to the size given as input
public User(String o, int boxsize) {
userName = o;
outbox = new Mailbox(boxsize);
inbox = new Mailbox(boxsize);
}
}
Here is the Message class:
/**
* Created by Broomhead0 on 4/11/14.
*/
public class Message {
// the properties of a message
private String sender;
private String receiver;
private String subject;
private String body;
// all property values are known at creation of the message; so initialize
public Message (String s, String r, String sub, String b)
{
sender = s;
receiver = r;
subject = sub;
body = b;
}
// any nice format of printing the names and the values of the properties will do
public void printMsg()
{
System.out.println("Sender: " + sender);
System.out.println("Receiver: " + receiver);
System.out.println("Subject: " + subject);
System.out.println("Message: " + body);
}
// what follows are basic getter methods
public String getSender()
{
return sender;
}
public String getReceiver()
{
return receiver;
}
public String getSubject()
{
return subject;
}
public String getBody()
{
return body;
}
}
public class MailboxSystemSol{
public static void main (String args[]) throws IOException{
//define userlist, user and message variables..
UserList userList = new UserList();
User user = new User("Matthew", 1024);
Message message = new Message("sender#gmail.com", "receiver#gmail.com", "Subject Content", "Body Content");
//do something with declared variables...
writeAllToFile(userList, user, message);
}
public static void writeAllToFile(Userlist ul, User u, Message me){
//code is too long to post here
}
}

Categories

Resources