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 :)
CodePudding user response:
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)
CodePudding user response:
I'm sure some good old printlns will show you what's going on:
public int addToValue(int valueChange){
System.out.println(String.format("Adding %s to %s", valueChange, value));
value = value valueChange;
System.out.println("Returning " value);
return value;
}
You'll see that your constructor is wrong and this.value is initially zero