vamsiampolu
vamsiampolu

Reputation: 6622

String condition check failing for test

I have a method to validate a grouper string:

public String validateGrouper(String grouper)
    {
        if(grouper!=null)
            grouper = grouper.trim();
        if(grouper==null || grouper.equals("") || !grouper.equalsIgnoreCase("AND") || !grouper.equalsIgnoreCase("OR"))
        {
            System.out.println("Trap for grouper validation triggered with grouper: "+grouper);
            grouper="AND";
        }
        else
            grouper = grouper.toUpperCase();
        return grouper;
    }

I am running it against this test:

@Test
public void testValidateGrouper(){
    DBUtils dbUtils = new DBUtils();
    assertEquals("Expect empty string to be replaced by AND","AND",dbUtils.validateGrouper(""));
    assertEquals("Expect spaced out string to be replaced by AND","AND",dbUtils.validateGrouper("   "));
    assertEquals("Expect the lower case and to be used as AND","AND",dbUtils.validateGrouper("and"));
    assertEquals("Expect the upper case AND to be used as AND","AND",dbUtils.validateGrouper("AND"));
    assertEquals("Expect the word CART to be ignored and replaced by AND","AND",dbUtils.validateGrouper("CART"));
    assertEquals("Expect AND to be used as the grouper if no grouper is provided","AND",dbUtils.validateGrouper(null));
    assertEquals("Expect the lower case or to be used as OR","OR",dbUtils.validateGrouper("or"));
    assertEquals("Expect the upper case OR to be used as OR","OR",dbUtils.validateGrouper("OR"));
}

I find that the condition is always triggered despite using AND and OR. I do not understand why the condition is failing.

Upvotes: 3

Views: 65

Answers (1)

Eran
Eran

Reputation: 393846

If either AND or OR are allowed, you need

if(grouper==null || !(grouper.equalsIgnoreCase("AND") || grouper.equalsIgnoreCase("OR")))

Otherwise, if grouper is "OR", it's not equal to "AND" and the condition is true, and if grouper is "AND", it's not equal to "OR" and the condition is true.

Also, you can remove the grouper.equals("") check.

Upvotes: 1

Related Questions