As it was highly recommended in one of the books I'm reading I've started to write tests for each of the class I'm creating. I'm not really sure what is a good practice to cover setters and getters or not. If yes I'm not sure how because to verify the setter method you need to call the getter for this variable and vice versa. So you will never know where the actual problem is.
Where I went is just similar tests for setters and getters. I don't really like it. Could you guys refer me to a right direction?
Thank you very much!
Normally I say not to test getters and setters because they get tested with other classes when they get used. You have logic in your setters though so it makes sense to test them. You asked how you know if the error is in the getter or setter. It turns out that it doesn't matter. If there is an error, you are going to need to look at it. And then you'll see what is wrong.
test the empty string case - you want to cover all the paths in your code by tests
assertTrue(card.getWeight() == 2); should be assertEquals("weight", 2, card.getWeight()); because it gives you a clearer error message when the test fails.
assertTrue(card.getForeignWord() == "test") should be assertEquals("foreign word", "test", card.getForeignWord());
you don't need to repeat the test in sepearate methods for the getter and setter. It is the same test
move instantiating Card to a @Before method to reduce duplicate code
And about the actual code:
if (foreignWord != "") is functionally incorrect - you should use equals() for comparisons
if the string isn't what you expect in a setter, you output a message. Do you want to throw an exception if the argument is invalid?
"==" tests if two variables refer to the same physical object. equals() tests whether two objects are equivalent. For String, "equivalent" means they have the same characters in the same order. You can have two different String objects with the same characters in the same order, and they'll look identical when printed. equals() would return true, but "==" would return false. That's why you want to use equals() to compare Strings.
Note, though, that the JVM keeps a pool of String literals. Every "test" that appears directly in your program refers to the same physical String object, so
"test" == "test"
is true. But, for example, if you read the String "test" from the console, and compare it to a literal "test" in your program, you'll see there's not the same object:
Ok, ok... please prove my guess. I have a feeling that on new object of String type is instantiated and because the "" is already on a string pool those two are actually the same object and thus is true? Because if I would use: