Search code examples
javaboolean-logicxor

method return boolean form xor


Using java, I have a method:

boolean shouldPointBeAdded(boolean excludePoint, shapeContainsPoint){
    return excludePoint ^ shapeContainsPoint;
}

used as:

if(shouldPointBeAdded(excludePoint, shape.contains(point))

This is used as an if condition, however it doesn't perform the same way as if I were to do XOR directly as the if condition.

Note: I've wrapped the XOR in a method for testing and readability.

When running the unit test cases, the asserts do not return the correct value when using the method shouldPointBeAdded(), however they do return the correct value when XOR is used directly in the if condition.

Thoughts??

Thanks.

UPDATE: Making shouldPointBeAdded() static solves the perceived problem, so I think the issues lies in with the mocking of the test objects.


Solution

  • The mock \ spy'd object was incorrectly set up. It wasn't initialised with the behaviour at the right time and with an incorrect object; this is what I believe from what I've observed.

    So, it was:

    when(spy.shouldPointBeAdded(excludePoints, shape.contains(mock(Point.class)))).thenCallRealMethod();
    

    I change it to:

    when(spy.shouldPointBeAdded(excludePoints, shape.contains(point)).thenCallRealMethod();
    

    exlcludePoints and shape are real objects, not mocks, that are passed into a set up method, and point is a test class member variable. point is assigned as necessary just before it is used.

    for(Point pointInGrid : buildTenByTenGrid()) {
                point = pointInGrid;
                if(objectUnderTest.shouldPointBeAdded(excludePoints, shape.contains(point))) {
                    pointsInShape.add(point);
                }
            }
    

    Tests working as expected now.