How can I JUnit test the last block of this equal?
Any help would be much appreciated. This is the method in question:
#Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
//unreachable block
ServiceOrderRelationship serviceOrderRelationship = (ServiceOrderRelationship) o;
return Objects.equals(this.id, serviceOrderRelationship.id) &&
Objects.equals(this.href, serviceOrderRelationship.href) &&
Objects.equals(this.relationshipType, serviceOrderRelationship.relationshipType) &&
Objects.equals(this.baseType, serviceOrderRelationship.baseType) &&
Objects.equals(this.schemaLocation, serviceOrderRelationship.schemaLocation) &&
Objects.equals(this.type, serviceOrderRelationship.type) &&
Objects.equals(this.referredType, serviceOrderRelationship.referredType);
}
This is what I've been doing but I can never reach the last block of code inside the equals method:
#Test
public void testEquals() throws Exception {
assertFalse(serviceOrderRelationship.equals(null));
assertTrue(serviceOrderRelationship.equals(serviceOrderRelationship));
assertFalse(serviceOrderRelationship.equals(serviceOrderRelationship1));
}
First of all, thank you all for your responses!
This is how I was able to reach the last block of the equals method. I had to initialize both objects di and di1 and set every variable to the same value, then test the equals condition switching back and forth one variable at a time to a different value. This is an example from another POJO:
// Initialize objects
di.setEdgeId("edgeId");
di.setIdentityEndpoint("identityEndpoint");
di.setUsername("username");
di1.setEdgeId("edgeId");
di1.setIdentityEndpoint("identityEndpoint");
di1.setUsername("username");
// Change value of var and test equal
di1.setEdgeId("edgeIdm");
assertFalse(di.equals(di1));
di1.setEdgeId("edgeId");
// same
di1.setIdentityEndpoint("identityEndpointm");
assertFalse(di.equals(di1));
di1.setIdentityEndpoint("identityEndpoint");
// Same
di1.setUsername("usernamem");
assertFalse(di.equals(di1));
di1.setUsername("username");
// Then at the end perform the other tests
assertTrue(di.equals(di));
assertTrue(di.equals(di1));
assertFalse(di.equals(null));
assertFalse(di.equals(42));
Your problem might be that one of the follow cases, in which the method would return prematurely.
If serviceOrderRelationship and serviceOrderRelationship1 are references to the same object, the true would be returned. Similarly, if they are not of the same type, false would be returned. If serviceOrderRelationship1 is null, false would be returned.
If serviceOrderRelationship is null, then calling equals on it would throw a NullPointerException.
Related
I have the first couple if checks in this equals implementation tested in junit but I can't figure out how to get pas the second if check to the final return check. Can someone help me figure this out :) I'll post my two assertions that get me past the first couple if checks. (Laila is my dog an in the code is a Pet object :)).
-- the code to test:
#Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(this.id, pet.id) &&
Objects.equals(this.category, pet.category) &&
Objects.equals(this.name, pet.name) &&
Objects.equals(this.photoUrls, pet.photoUrls) &&
Objects.equals(this.tags, pet.tags) &&
Objects.equals(this.status, pet.status);
}
These are the assertions I have that get me past the first two if checks:
assertTrue(laila.equals(laila));
assertFalse(laila.equals(null));
You need to compare with another Pet object that is not the same reference or null.
assertFalse(laila.equals(new Pet(/* instantiate different pet */)));
The following Java snippet of code confuses me a bit. The method is trying to check whether two objects are NOT equal, using the standard .equals() method to denote that they are equal. Additionally, a boolean can determine whether two null's are considered equal or not. I'm wondering if:
The boolean logic in this method is indeed correct?
the return statement in the middle block can be omitted somehow. Could this logic be rewritten in a more concise or other way, maybe dropping the empty return, but keeping a high level of human readability of the code?
Snippet:
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual)
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable == null || otherVariable == null)
{
return;
}
if(variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Yes, the logic in the method is correct. It throws the exception if the two objects are equal. You could remove the second condition and combine it with the third one, but I don't see much point. If you did, the method might look like this.
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual) throws Exception
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable != null && variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Note that there's no need to check whether otherVariable is null separately, since the equals method on variable should return false if otherVariable is null.
There's an even more concise way to write this, but it's not worth considering, since it sacrifices readability.
I'm doing an assignment that asks me to override the equals method of a house class.
The instructions are as follows:
Two houses are equal when their building areas are equal and their pool status is the same
Until now, this is what I've wrote:
#Override
public boolean equals(Object other) {
if (other instanceof House) {
House otherHouse = (House) other;
return otherHouse.calcBuildingArea() == ???
&& otherHouse.mPool == ???
} else {
return false;
}
}
Now I don't know what to write after the == signs. I don't know how to specify the object that calls the method.
If you call a method without specifying an object, the method will get called on the current object. So you can write
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& otherHouse.mPool == mPool;
or if you want to make it nice and clear and explicit, you can write
return otherHouse.calcBuildingArea() == this.calcBuildingArea()
&& otherHouse.mPool == this.mPool;
Note also that this assumes that mPool is of a primitive type or an enum type. If it's a reference type, such as String, you may need to invoke its equals method like
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& otherHouse.mPool.equals(mPool);
or even the more null-friendly
return otherHouse.calcBuildingArea() == calcBuildingArea()
&& Objects.equals(otherHouse.mPool, mPool);
How about this?
return otherHouse.calcBuildingArea() == this.calcBuildingArea()
&& otherHouse.mPool == this.mPool
I'm trying to make a bit of code that returns a boolean value depending on whether an item was successfully removed from a HashMap or not.
My understanding is that map.remove(Key) should return the Key if it worked and null if not. My approach was to check if the return value is null and print false if it is, true if anything else.
The problem I'm having comes from that I don't know how to check what the return value was inside my method.
Here is my attempt so far.
public boolean deleteMapEntry(String entry)
{
testMap.remove(entry);
if(null)
{
return false;
}
else
{
return true;
}
}
Obviously saying if (null) doesn't work, but I can't find what would.
You need to assign the value of testMap.remove(entry) to a variable to test it to see if it is null...
String value = testMap.remove(entry);
return value != null;
you can also just test what you remove directly and not use a variable:
return testMap.remove(entry) != null;
I have the following code in a class used to simulate the IRS with employer filings in accordance with the filer. I am required to override the equals class but I keep getting the error saying that the methods I am trying to use cannot be found when called on the casted Object.
#Override
public boolean equals(Object obj) {
if ((this == null )|| (obj == null) || (this.getClass() != obj.getClass()))
return false;
if ((this.sameEmployer((Employer)obj))
&& (this.getEmployeeSSN() == (Employer)obj.getEmployeeSSN())
&& (this.getName() == (Employer)obj.getName())
&& (this.getEmployeeName() == (Employer)obj.getEmployeeName())
&& (this.getEmployeeWages() == (Employer)obj.getEmployeeWages()))
return true;
else
return false;
}
Casting happens after method calls. According to the precedence of operators, () for method calling is at the highest level, 1, while () for casting is at level 3. In other words you are attempting to cast obj.getEmployeeSSN() as an Employer, not obj.
Once you know obj is an Employer, you can place parentheses to force casting first, e.g.
&& (this.getEmployeeSSN() == ((Employer) obj).getEmployeeSSN())
However, it looks like a mess of parentheses. For clarity, just declare an Employer variable, cast it once, then call the methods, passing the Employer variable.
Employer emp = (Employer) obj;
if (this.sameEmployer(emp)
&& ...
For expressions like this:
(Employer)obj.getEmployeeSSN()
The . has higher precedence - "binds tighter" - than the cast. So it's closer to:
(Employer) (obj.getEmployeeSSN())
... whereas you want:
((Employer) obj).getEmployeeSSN()
in order to cast and then call the method. That's most easily done by casting in an earlier line:
public boolean equals(Object obj) {
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
Employee other = (Employee) obj;
// Now use "other" in the rest of the code:
return sameEmployer(other)
&& getEmployeeSSN() == other.getEmployeeSSN()
...;
}
Note that:
this can never be null, so you don't need to test it
You don't need nearly as many brackets as you had before
I'd strongly encourage you to use braces for all if blocks... you'd be surprised at how easy it is to end up with mistakes otherwise. (There are lots of SO questions which are basically due to that...)
Any time you have:
if (foo) {
return true;
} else {
return false;
}
you should simplify it to:
return foo;
Class Object doesn't have getEmployeeSSN(). What you should have instead is :
(this.getEmployeeSSN() == ((Employer)obj).getEmployeeSSN() //and so forth.
The cast should happen first, then you try to use the method on the casted object
You just have a problem with priority of your operations. The cast to (Employer) will happen after you call the specific methods. To enforce the priority you need to add brackets:
((Employer) obj).getName()
instead of
(Employer) obj.getName()