Skip to content
Advertisement

JUnit4 – Trying to make my constructor work with my unit tests

So as you will be able to see in the code, my class constructor asks the user for an input of the “initialValue” of their object. I then have a method “addToValue” which adds to that value. When trying to use JUnit4 to learn TDD it does not use the “initialValue” parameter to set the value of “value”, therefore it is only returning the input of the “valueChange” parameter. Sorry if this is confusing.

Here is my code

public class Sterling {
    int value;
    public Sterling(int initialValue) {
        int value= initialValue;


    }
    public int addToValue(int valueChange){;
        value = value+valueChange;
        return value;
    }
}

This is the JUnit4 code

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class SterlingTest {

    private Sterling o;

    @Before
    public void setUp() {
        o = new Sterling(100);
    }

    @Test
    public void testAddToValue(){
            assertEquals(150,o.addToValue(50));

    }}

in the “assertEquals” line, 150 is the expected return value (initalValue is 100 and valueChange is 50) however my “Actual” output value is 50. As mentioned before I am only just learning to use JUnit so I’m sure its a simple mistake but I have been stuck on this for nearly 2hours lol.

Thank you for any help 🙂

Advertisement

Answer

As spiders mentioned in the comments your line

int value= initialValue;

creates a variable that is only accessible in scope for the constructor method. The class field value will not be set to anything and thus will have the default value for an unassigned int, which is 0

If you change that line to

value = initialValue;

or

this.value = initialValue;

you should see the behavior you want as you will be setting the value for the value field of your object (instead of a local value variable)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement