这是我测试的课程:
public class MovieListing implements Listing {
private BitSet keyVectors = new BitSet();
private int year;
private String title;
private Set<String> keywords;
public MovieListing(String title, int year) throws ListingException {
if (title == null || title.isEmpty() || year <= 0) {
throw new ListingException("Missing Title or year <= 0");
}
this.title = title;
this.year = year;
keywords = new TreeSet<String>();
}
public void addKeyword(String kw) throws ListingException {
if (kw == null || kw.isEmpty()) {
throw new ListingException("Missing keywords");
}
this.keywords.add(kw);
}
这是对addKeyword方法的测试:
@Before
public void setup() throws Exception {
movieList = new MovieListing(null, 0);
}
@Test
public void addKeywords() throws Exception {
assertEquals(0, movieList.getKeywords().size());
movieList.addKeyword("test1");
assertEquals(1, movieList.getKeywords().size());
movieList.addKeyword("test2");
assertEquals(2, movieList.getKeywords().size());
}
出了什么问题?它无法通过。谢谢你的任何建议!
如何在课堂上测试例外,因为如果我使用@Test(expected=Exception.class)
答案 0 :(得分:1)
您正在使用title
初始化null
:
@Before
public void setup() throws Exception {
movieList = new MovieListing(null, 0);
}
然后你在构造函数中抛出一个异常,如果它是null
:
if (title == null || title.isEmpty() || year <= 0) {
throw new ListingException("Missing Title or year <= 0");
}
答案 1 :(得分:1)
尽管如果你传递null
,或者year
为0,你就会调用错误条件(感谢这个奇妙的条件,可能< / em>完全有效):
if (title == null || title.isEmpty() || year <= 0) {
throw new ListingException("Missing Title or year <= 0");
}
...您以某种方式或容量错过了keywords
集的曝光。
由于您的方法为void
,因此您无法断言您将从该方法返回的内容。因此,您必须检查您正在处理的实体的内部状态。
使用keywords
字段上的包私有getter很容易实现:
Set<String> getKeywords() {
return keywords;
}
此时,请确保您的测试类与实际代码位于同一个包中。
此外,我建议不要在init
中设置那种初始数据。我认为每个单独的测试都需要初始化我们想要测试的实体。将实例化移动到测试本身内是一件简单的事情。