I'm trying to create a method where it outputs a certain number of stars based on the rating of a movie. I'm using the toString method, but am unsure of how to call this in my tests. When I attempt to write the tests, it says that "Non-static method cannot be referenced from a static context". I'm trying to use assertEquals to see if it's outputting the desired result with "assertEquals("***", Rating.toString());". My other methods had the same problem so I made them static, but this is not an option with the toString method. Is it acceptable to simply make the other methods static, or is the message likely hinting at a different flaw (or flaws) in my methods and/or tests? This may actually result in the same answer if it's a bigger problem within the code, but how would I go about testing toString when it gives the same message (non-static method cannot referenced..) when toString cannot be static?
I have reviewed other questions about the toString method and testing, but am having trouble relating it to my own code. Also, I'm not sure if I'm dealing with one error or multiple which is making it a difficult problem to solve. Help would be very much appreciated.
public class Rating {
public static int votes;
public static double score;
public static String result;
public Rating() {
votes = 0;
score = 0;
}
public static void resetVotes(){
Rating.votes = 0;
Rating.score = 0;
}
public static int getNumVotes(){
return Rating.votes;
}
public static void addVote(double rating){
Rating.votes = Rating.votes + 1;
Rating.score = Rating.score + rating;
}
public static double computeScore() {
return (Rating.score / Rating.votes);
}
public String toString() {
if (Rating.votes > 1)
{
if (computeScore() > 1 && computeScore() < 2)
{
result = "*";
}
else if (computeScore() > 2 && computeScore() < 3)
{
result = "**";
}
else if (computeScore() > 3)
{
result = "***";
}
else if (computeScore() < 1)
{
result = " ";
}
}
return result;
}