我目前正在编写一个需要一些示例JUnit测试的程序。我的计划的目标是按照导演的字母顺序对电影进行分类。我正在使用Comparator
课程,该课程将ArrayList
Movies
,并按导演的字母顺序对其进行排序。
问题1 :无法使用"添加"我的JUnit
测试类中用于将Movies
添加到ArrayList
的方法,为什么会有任何想法?
第2期:如何将DirectorComparator
作为JUnit
测试用例进行测试?
Movie.java:
import java.util.*;
public class Movie {
String title;
String director;
public Movie(String title, String director) {
this.title = title;
this.director = director;
}
public String getAuthor() {
return author;
}
public static Comparator<Movie> DirectorComparator = new Comparator<Movie>() {
public int compare(Movie movie1, Movie movie2) {
String director1 = movie1.getDirector();
String director2 = movie2.getDirector();
return director1.compareTo(director2);
}
};
MovieTest.java
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class MovieTest {
Movie movie1("Star Wars", "Lucas, George");
Movie movie2("ET", "Spielberg, Steven");
Movie movie3("The Godfather", "Coppola, Francis Ford");
ArrayList<Movie> Movies = new ArrayList<Movie>();
Movies.add(movie1); <=== FIRST ISSUE, CANNOT USE "ADD"??
@test
<===== SECOND ISSUE, WHAT TYPE OF STRUCTURE TO USE FOR THE DIRECTORCOMPARATOR TEST CASE??
在这里真的很感激任何帮助!
答案 0 :(得分:0)
首先让我们简化你的比较器实现:
public class Movie {
private String title;
private String director;
public Movie(String title, String director) {
this.title = title;
this.director = director;
}
public static final Comparator<Movie> DirectorComparator =
Comparator.comparing(movie -> movie.director);
}
然后让我们为所有可能的案例编写测试:
public class MovieTest {
@Test
public void directorComparatorReturnsZeroWhenSameDirectors() {
// given
Movie movie1 = new Movie("Star Wars", "Lucas, George");
Movie movie2 = new Movie("Star Wars", "Lucas, George");
// when
final int actualResult = Movie.DirectorComparator.compare(movie1, movie2);
// then
Assert.assertEquals(0, actualResult);
}
@Test
public void directorComparatorReturnsNegativeWhenSecondDirectorGreater() {
// given
Movie movie1 = new Movie("Star Wars", "Lucas, George");
Movie movie2 = new Movie("Star Wars", "Mucas, George");
// when
final int actualResult = Movie.DirectorComparator.compare(movie1, movie2);
// then
Assert.assertEquals(-1, actualResult);
}
@Test
public void directorComparatorReturnsPositiveWhenFirstDirectorGreater() {
// given
Movie movie1 = new Movie("Star Wars", "Mucas, George");
Movie movie2 = new Movie("Star Wars", "Lucas, George");
// when
final int actualResult = Movie.DirectorComparator.compare(movie1, movie2);
// then
Assert.assertEquals(1, actualResult);
}
}
顺便说一句,为了完成原始测试,您应该通过这种方式添加电影:
Movie movie1 = new Movie("Star Wars", "Lucas, George");
Movie movie2 = new Movie("ET", "Spielberg, Steven");
Movie movie3 = new Movie("The Godfather", "Coppola, Francis Ford");
List<Movie> movies = new ArrayList<>();
movies.add(movie1);
movies.add(movie2);
movies.add(movie3);
但这个集合根本与DirectorComparator
无关。因此,在DirectorComparator
的测试中不需要它。