Java J-unit tests - java

I am testing a class that was implemented from an interface.
In my test class, I have created objects (Humains) that have a name and bank account value.
One of my methods to test takes an arrayList and compares with another list and if the person already exists, the amount will be added.
Code is something like that:
TEST CLASS
HumainImpl<Humain> humain = new HumainImpl<Humain>();
private Humain h1 = new Humain("AAA" , 2200);
private Humain h2 = new Humain("DDD" , 500);
#Test
public void testAddAmount(){
List<Humain> testing = new ArrayList<Humain>();
testing.add(h1);
testing.add(h2);
humain.placeList(testing);
}
the placeList(testing) method is in the HumainImpl class which calls another method in the Humain class that does the addition.
In the HumainImpl class there is also a list called implList.
Once this method placeList is called, the numbers for h1 and h2 in the test class are changing.
What I want, is that only the number for the implList to change.
Is it something normal that when adding up numbers or making changes while passing the h1 and h2 as parameter they will get effected ?
I have tried too many ways and I don't get it. I tried going through the list passed as a parameter copy the element in that list into another attribut and do the addition but it didn't help.
This works fine when I test another similar method that takes an element as a attribut, place(h1).
Test Class:
HumainImpl<Humain> humain = new HumainImpl<Humain>();
private Humain h1 = new Humain("AAA" , 2200);
private Humain h2 = new Humain("DDD" , 500);
#Test
public void testAddAmount(){
List<Humain> testing = new ArrayList<Humain>();
testing.add(h1);
testing.add(h2);
humain.placer(testing); //placer(testing) is the method placer with a list parameter
}
HumainImpl:
private boolean existe(T elt){
boolean result = false;
index = uneListe.indexOf(elt);
if(index >= 0){
result = true;
}
return result;
}
#Override
public boolean placer(T elt) {
boolean result = false;
boolean found = false;
int i = -1;
int nbExemple;
if(elt != null){
boolean existe = existe(elt);
nbExemple = nbExemplaires(elt);
if(uneListe.size() > 0 && existe){
while(!found && i < uneListe.size()){
i++;
if(elt.equals(uneListe.get(i))){
found = true;
}
}
T element = uneListe.get(i);
nbExemple = element.retournerNbExemplaires();
elt.additionner(nbExemple);
result = false;
} else if(!existe && nbExemple >= 1 &&
uneListe.size() < nbPlacesMaximum) {
uneListe.add(elt);
result = true;
}
}
return result;
}
#Override
public void placer(List<T> liste) {
iterateur(liste);
while(liste != null && liste.size() > 0 && itList.hasNext()){
placer(itList.next());
}
}
In the class Humain:
#Override
public void additionner(int nbExemplaires) {
this.nbExemplaires += nbExemplaires;
}
#Override
public int retournerNbExemplaires() {
return nbExemplaires;
}

Related

Why does the counter inside if statement not work?

Hello friends I am trying to build a class Car for a project. There are many methods inside the following code as well as an if statement that I am having trouble building, consider the following code
public class Car extends Vehicle {
private boolean isDriving;
private final int horsepower;
private boolean needsMaintenance = false;
private int tripsSinceMaintenance = 0;
Car() {
super();
this.horsepower = 0;
this.isDriving = false;
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
public int getHorsepower() {
return this.horsepower;
}
public boolean getDrive() {
return this.isDriving;
}
public boolean getMain() {
return this.needsMaintenance;
}
public int getTRIP() {
return this.tripsSinceMaintenance;
}
public void drive() {
this.isDriving = true;
}
public void stop() {
this.isDriving = false;
}
public void repair() {
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
/**
* #param args
*/
public static void main(String[] args) {
Car auto = new Car();
auto.drive();
auto.stop();
if (auto.isDriving == true) {
if (auto.isDriving == false)
auto.tripsSinceMaintenance = auto.tripsSinceMaintenance + 1;
}
if (auto.tripsSinceMaintenance > 100)
auto.needsMaintenance = true;
System.out.println("Drive: " + auto.getDrive());
System.out.println("trip: " + auto.getTRIP());
}
}
What I want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenanceis greater than 100,needsMaintenanceshould becometrue`.
here I expected trips to be 1 but the result is the following:
Drive: false
trip: 0
I have tried this.isDriving==true; and basicaly wherever auto is inside the if statement I put this but the following error appears
non static variable cannot be referenced from static context
help me please!
What i want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenance is greater than 100 needsMaintenance should become true
Do this inside stop() method
fun stop() {
if (isDriving) {
tripsSinceMaintenance++;
}
if (tripsSinceMaintenance > 100) {
needsMaintenance = true;
}
isDriving = false;
}
You don't need to put == true inside of an if statement, it's doing that already,
if(someCondition) { // <-- this executes if the condition is true.
Also, you have conflicting conditions nested, meaning...
if (thisIsTrue) {
if (!thisIsTrue) {
// <--- unreachable statements
where you should be incrementing your variable is where you're setting "isDriving = true"
So your code would look like this:
public void drive() {
this.isDriving=true;
auto.tripsSinceMaintenance++;
}

Trying to assign value to array elements and return it in another class to work with but not working

I am having diffculty with trying to assign value to array elements based on a userinput and checking the array element's value in another class. When I do that I get null and I am not sure why and how to fix it.
I have no expereince with java, just started learning it and doing it as part of uni course.
Any help is appreciated and thank you.
Class 1
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
Class 2
public class MainProgram {
public static void main(String[] args) {
UserInterface input = new UserInterface();
input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
String check[] = checkError.getError();
if (check[0] == ("Hello")) {
System.out.println("yh");
}
}
}
I think you're confusing your method calls a bit. In class 2, you have a line:
String check[] = input.getError();
That should probably be:
String check[] = checkError.getError();
As the getError() method is in your first class (ErrorHandling) and not the UserInterface class.
Also, you assign Hello to errorMessage[0] and not hey, so that might be failing in your last few lines in class 2.
If you're just starting out with Java I recommend reading up on Class Structure to understand this (as well as Arrays).
**EDIT
String comparison in Java doesn't work using the == operator. As they are objects and not primitive data types, you must use .equals.
check[0].equals("Hello")
Invoke checkError.inputCheck() in the main program otherwise errorMessage will not get initialized.
Some tweaks in your code that will help to execute:
Class 1
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
// If you want to use askZigZag... use it somewhere inside this function
// since you have already declared the object of UserInterface.
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
Class 2
public class MainProgram {
public static void main(String[] args) {
// UserInterface input = new UserInterface();
// input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
checkError.inputCheck();
String check[] = checkError.getError();
if (check[0].equals("Hello")) {
System.out.println("yh");
}
}
}

flag always returns 0 to another class

import java.util.ArrayList;
import java.util.List;
public class QueryParser {
QueryParameter queryParameter = new QueryParameter();
public static int flag = 0;
public QueryParameter parseQuery(String queryString) {
queryParameter.setGroupByFields(getGroupByFields(queryString));
queryParameter.setAggregateFunctions(getAggregateFunctions(queryString));
return queryParameter;
}
private List<AggregateFunction> getAggregateFunctions(String queryString) {
List<AggregateFunction> aggregateFunctionList = null;
AggregateFunction aggregateFunction;
if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
|| queryString.contains("max") || queryString.contains("avg")) {
flag = flag + 1;
}
return aggregateFunctionList;
}
private List<String> getGroupByFields(String queryString) {
List<String> groupByFieldList = null;
if (queryString.contains("group by")) {
flag = flag+2;
return groupByFieldList;
}
}
this is my code, now i am accessing flag from another class using
int i = queryParser.flag,
but it always returns 0. How to declare flag so that it will hold the values from the inner methods and also can be accessed from other classes. /* if anyone need more details please ask i'll add more details, and what more should i write,my main doubt is only to know how i can utilise my flag in another class, thank you for being patient*/
An MCVE could look like this:
public class QueryParser {
public static int flag = 0;
void getAggregateFunctions(String queryString) {
if (queryString.contains("count") || queryString.contains("sum") || queryString.contains("min")
|| queryString.contains("max") || queryString.contains("avg")) {
flag = flag + 1;
}
}
void getGroupByFields(String queryString) {
if (queryString.contains("group by")) {
flag = flag+2;
}
}
public static void main(String[] args) {
QueryParser q = new QueryParser();
System.out.println(flag); //prints out 0
q.getAggregateFunctions("max"); System.out.println(flag); //prints out 1
q.getAggregateFunctions("aString"); System.out.println(flag); //prints out 1
q.getAggregateFunctions("avgNumber"); System.out.println(flag); //prints out 2
q.getGroupByFields("group by"); System.out.println(flag); //prints out 4
}
}
It helps those who want to help you, and far more important: it is a great debugging tool.
Making on helps you isolate the problem, and focus on it.
Like in this case: you can see that the problem is not in the declaration of flag, nor changing its value, but maybe with the input values.

Sets intersection

I want to apply the inteserction ( using this method http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Sets.html) to sets that contain objects not primitive. I wrote this code but I have that the intersection is empty..
Concept a = new Concept("Dog");
Concept b = new Concept("Tree");
Concept c= new Concept("Dog");
HashSet<Concept> set_1 = new HashSet<Concept>();
HashSet<Concept> set_2 = new HashSet<Concept>();
set_1.add(a);
set_1.add(b);
set_1.add(c);
SetView<Concept> inter = Sets.intersection(set_1,set_2);
System.out.println(inter.size()); ----> I HAVE ZERO !!!
The Concept class contains only a private member of type String and the method of get and set ..I don't have equals() and hashCode().
This works as expected (notice equals and hashCode on Concept)
package com.stackoverflow.so19634761;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.util.Set;
public class ISect {
public static void main(final String[] args) {
final Concept a = new Concept("Dog");
final Concept b = new Concept("Tree");
final Concept c= new Concept("Dog");
final Set<Concept> set1 = Sets.newHashSet(a);
final Set<Concept> set2 = Sets.newHashSet(b, c);
final SetView<Concept> inter = Sets.intersection(set1, set2);
System.out.println(inter); // => [Concept [data=Dog]]
}
private static class Concept {
private final String data;
// below this point code was generated by eclipse.
public String getData() {
return data;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Concept other = (Concept) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
return true;
}
public Concept(String data) {
this.data = data;
}
#Override
public String toString() {
return "Concept [data=" + data + "]";
}
}
}
You are putting Concept inside Sets, not the Strings - Dog, Tree. U also need to override the hashcode and equals of the concept class for it to work
At first, You need to override equals and hashcode method on Concept class. You don't need third party library. Just use
set_1.retainAll(set2);
set_1.retainAll(set2) transforms set_1 into the intersection of set_1 and set_2. (The intersection of two sets is the set containing only the elements common to both sets.).

NullPointerException.. Where is the flaw in my logic?

In Main:
Equipe Eq1 = new Equipe(J,E);
Equipe Eq2 = new Equipe(J,E);
while(Eq1.equals(Eq2))
Eq2 = new Equipe(J,E);
Match m = new Match(Eq1,Eq2);
String ChercherJoueur = m.QuelEquipe(m.hasBall());
In Class Equipe:
public Vector<Joueur> VJ;
public Equipe(Vector<Joueur> E, Vector<Entraineur> Ent) {
VJ = new Vector<Joueur>();
//rest of the logic
}
public Equipe() {
}
In Class Match:
Equipe Eq1 = new Equipe();
Equipe Eq2 = new Equipe();
public Match(Equipe Eq1, Equipe Eq2) {
Eq1 = this.Eq1;
Eq2 = this.Eq2;
}
public String QuelEquipe(Joueur J)
{
boolean found = Eq1.ChercherJoueur(J);
if(found == true)
return "EQ1";
else
return "EQ2";
}
public Joueur hasBall()
{
Joueur J = null;
int i = 0;
boolean found = false;
NullPointerException-------> System.out.println(Eq1.VJ.get(i).isBall());
System.out.println(Eq2.VJ.get(i).isBall());
while(!found)
{
if((Eq1.VJ.get(i).isBall())==true)
{
found = true;
J= Eq1.VJ.get(i);
}
else if((Eq2.VJ.get(i).isBall())==true)
{
found = true;
J= Eq2.VJ.get(i);
}
i++;
}
return J;
}
}
I think is all I need to include here to inform u about the situation.. I get a NullPointerException when I do "m.QuelEquipe(m.hasBall());" that can be traced back to where I pointed in The Class Match.. I know exactly what the exception means, and I'm changing their references with "Eq1 = this.Eq1;Eq2 = this.Eq2;" anyway.. sooo where is flow to get the code to work??
Your constructor using two args does initialize the vector but the parameterless constructor doesn't
public Equipe(Vector<Joueur> E, Vector<Entraineur> Ent) {
VJ = new Vector<Joueur>(); //<-- OK
//rest of the logic
}
public Equipe() {
//<-- errrk
}
Then when you invoke:
System.out.println(Eq2.VJ.get(i).isBall());
You're using really invoking:
Eq2.null.get <-- NullPointerException
But the real problem though is in the Match constructor:
public Match(Equipe Eq1, Equipe Eq2) {
Eq1 = this.Eq1;
Eq2 = this.Eq2;
}
Here you're assigning to the local variable Eq1 the value of the instance variable Eq1 you really want it the other way around:
public Match(Equipe Eq1, Equipe Eq2) {
this.Eq1 = Eq1;
this.Eq2 = Eq2;
}
BTW, this is not C# and in Java as a coding conventions both, methods and attributes start with lowecase and opening brace goes in the same line ( although this last part is not as relevant as the naming convention )
I hope this helps.
You are calling the default constructor public Equipe() which does not initialize VJ. Just remove the constructor if you are not going to use it.
This will fix your problem:
Match.java
private final Equipe eq1;
private final Equipe eq2;
public Match(final Equipe eq1, final Equipe eq2)
{
this.eq1 = eq1;
this.eq2 = eq2;
}

Categories