Reputation: 1715
Lets say we have following class:
package com.porphyrie.examples;
public class TestExample {
private String name;
private int id;
public TestExample() {
setName("testExample");
setId(3);
}
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}
}
How should I test this class? Since eclipse wants only to test the public methods, how I should test the getters without setting the setters? Is it valid to set the private
setter-methods in the class above to public
only for testing purposes?
Thanks for any help...
Upvotes: 0
Views: 2090
Reputation: 1311
No your private method can't be called from your unit test cases. so either you have to make it public or default or protected(if you have put it in the same package). You usually don't test private methods because they can only (normally) be tested indirectly through another public method. When you're test driving and make private methods then they are usually a result of an "extract method" refactoring and are already by then tested indirectly.
Upvotes: 0
Reputation: 2621
Your example code is a good example of code not written to enable easy unit testing. If you adopt the mindset that you have to design/structure/write your code in a way that makes it easier for you to test, then you shouldn't have these questions. Short answer, yes, expose setters as public to enable your testing, or package/default scope if you don't want the setters part of the public api.
Alternatively, you could add another constructor with parameters to set the values for you when you create an instance.
Upvotes: 2
Reputation: 779
You should not make setters private as the purpose of setters is for the programmer implementing a class to set values that they want to into the fields of the class. It is kind of redundant to have private setters as the fields are already private. If you don't what the fields to be mutated then leave the fields as private and don't create setters for these fields.
So yes is the answer to your question.
If you have a reason for not making your setters public, then you can use a parameterized contructor which initiates the fields with values passed as parameters when an object of this class is created and calling the parameterized constructor when instantiating the object.
Upvotes: 0