Search code examples
javastringunit-testingjunit

How does assertTrue and assertFalse work in Java?


I am trying to learn these and can not understand why it is not working, and the test itself is giving me no help in identifying what is wrong.

I updated my code trying to

Here is my class with the method:

package JUnit;

public class JUnitTesting {

    int number = 2;
            
        public boolean equalsTest(boolean equals){
            if(number == 2) {
                equals = true;
            }
            else if(number != 2) {
                equals = false;
            }
            return equals;
        }
    }
        

Here is the test:

package JUnit;

//Import in some functions
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class JUnitTest{
    
@Test
    public void equalsTest() {
        JUnitTesting equals = new JUnitTesting();{
            assertTrue(equals.equalsTest(false));
        }
    }

@Test
public void equalsTestTwo() {
    JUnitTesting equals = new JUnitTesting();{
        assertFalse(equals.equalsTest(false));
        }
    }
}

The first is passing the test when it should fail and I do not know why, and the second is failing when it should be passing. All it says is java.lang.AssertionError. Thanks in advance for any answers.


Solution

  • You have many problems with your code.

    1) The equals parameter

    Your JUnitTesting.equalsTest(boolean) method does not use the argument provided. It seems like you are confusing variables and arguments. An argument should be used when passing input.

    Your class method should look like this:

    public class JUnitTesting {
        int number = 2;
                
        public boolean equalsTest(){
            return number == 2;
        }
    }
    

    2) Unnecessary Scoping

    It appears that you made a mistake and copied and pasted it:

    JUnitTesting equals = new JUnitTesting();{
        assertTrue(equals.equalsTest(false));
    }
    

    This code scopes the assertion, when you did not intend to.

    3) You don't know what your code does

    If you took the time to write your code correctly, or if you took time to read your own code, you would know that the result of equalsTest, in no way, relies on the input. Therefore, any unit testing you do will essentially be a useless test. This is because it returns the same thing every time.

    So really, your unit tests are executing the following:

    1. assertTrue(true)
    2. assertFalse(true)

    Because true == true, your first test must pass. And because true != false, your second test must fail.