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

JavaScript

This is the JUnit4 code

JavaScript

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

JavaScript

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

JavaScript

or

JavaScript

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