class VoteServiceTest { private VoteService voteService; private ArticleVote updatedVote; private ArticleVote vote; private Article article; private User user; @BeforeEach void setUp() { initObjects(); voteService = new VoteService(); } @Test void addVoteUp() { vote.setVoteType(VoteType.VOTE_UP.toString()); Assert.assertEquals(1, voteService.addVote(article, vote).getVotes()); } @Test void addVoteDown() { vote.setVoteType(VoteType.VOTE_DOWN.toString()); Assert.assertEquals(-1, voteService.addVote(article, vote).getVotes()); } @Test void updateVoteFromUpToDown() { vote.setVoteType(VoteType.VOTE_UP.toString()); article.setVotes(1); user.getArticleVotes().add(vote); updatedVote.setVoteType(VoteType.VOTE_DOWN.toString()); Assert.assertEquals(-1, voteService.updateVote(article, updatedVote, vote).getVotes()); } @Test void updateVoteFromDownToUp() { vote.setVoteType(VoteType.VOTE_DOWN.toString()); article.setVotes(-1); user.getArticleVotes().add(vote); updatedVote.setVoteType(VoteType.VOTE_UP.toString()); Assert.assertEquals(1, voteService.updateVote(article, updatedVote, vote).getVotes()); } @Test void updateVoteFromUpToUp() { vote.setVoteType(VoteType.VOTE_UP.toString()); article.setVotes(1); user.getArticleVotes().add(vote); updatedVote.setVoteType(VoteType.VOTE_UP.toString()); Assert.assertEquals(1, voteService.updateVote(article, updatedVote, vote).getVotes()); } private void initObjects() { user = new User(); user.setUsername("user"); user.setPassword("password"); article = new Article(); article.setId(1L); article.setTitle("Testing"); article.setVotes(0); article.setUser(user); user.getAddedArticles().add(article); vote = new ArticleVote(); vote.setUser(user); vote.setArticle(article); updatedVote = new ArticleVote(); updatedVote.setArticle(article); updatedVote.setUser(user); } } @Service public class VoteService { public Activity addVote(Activity activity, Vote vote) { if (vote.getVoteType().equals(VoteType.VOTE_UP.toString())) { activity.setVotes(activity.getVotes() + 1); } else { activity.setVotes(activity.getVotes() - 1); } return activity; } public Activity updateVote(Activity activity, Vote vote, Vote previousVote) { if (previousVote.getVoteType().equals(vote.getVoteType())) { return activity; } else { previousVote.setVoteType(vote.getVoteType()); if (vote.getVoteType().equals(VoteType.VOTE_UP.toString())) { activity.setVotes(activity.getVotes() + 2); } else { activity.setVotes(activity.getVotes() - 2); } return activity; } } }