Reputation: 101
Teacher wanted us to do a comprehensive unit test. For me, this will be the first time that I use JUnit. I am confused about testing set and get methods. Do you think should I test them? If the answer is yes; is this code enough for testing?
public void testSetandGet(){
int a = 10;
Class firstClass = new Class();
firstClass.setValue(10);
int value = firstClass.getValue();
Assert.assertTrue("Error", value==a);
}
In my code, I think if there is an error, we can't know that the error is deriving because of setter or getter.
Upvotes: 10
Views: 23788
Reputation: 9538
I would say don't write unit tests for setters and getters, unless your setters and getters contain program logic (something getting computed as the setter or getter is called).
On a real project you will have more than plenty program logic to unit test without having to test something trivial like setters and getters.
Upvotes: 19
Reputation: 588
If you wanted to test it you could temporarily make the variable public and then:
firstClass.setMyInt(5);
Assert.assertTrue(5, firstClass.myInt);
However getters and setters can be automatically generated, they typically only contain one line in the method and if they cause your code to fail you probably have bigger problems. It's not common practise with unit testing to bother testing the getters and setters and you can avoid testing them and your unit testing will still be comprehensive.
Upvotes: 1
Reputation: 457
I think it is important if you have some conditions in it. For exemple if it return an exception, if your int must be positive or some other conditions. But if it is just a variable assignation, I don't think it is useful... It is the same for getters.
Upvotes: 3
Reputation: 19225
Dont unit test anything that relies on things outside of the class under test to work.
If your getters and setters are trivial then they can only fail if the underlying JVM/compiler fails - so you're actually testing the JVM/compiler, not your code.
Upvotes: 1
Reputation:
Roy Osherove in his famous book 'The Art Of Unit Testing' says:
Properties (getters/setters in Java) are good examples of code that usually doesn’t contain any logic, and doesn’t require testing. But watch out: once you add any check inside the property, you’ll want to make sure that logic is being tested.
You are testing what you set, can also be "get". Change your Assert
statement to:
Assert.assertTrue(a, true);
Also, you should pass a
, if you are going to use it.
Upvotes: 6
Reputation: 62854
If I were you, I would first set
some value to a property in the class I'm testing, and then I will make sure that the get
method returns the same value.
public void testSetandGet(){
int a = 10;
Class firstClass = new Class();
firstClass.setValue(10);
int value = firstClass.getValue();
Assert.assertEquals(value, a);
}
Upvotes: 2