[英]How to test this void method in java?
这是我正在测试的课程:
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)
则该异常不起作用
您要在此处初始化null
title
:
@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");
}
尽管如果传入null
或year
为0,您将要调用错误条件,这要归功于:(由于这种奇妙的条件,这可能是完全有效的):
if (title == null || title.isEmpty() || year <= 0) {
throw new ListingException("Missing Title or year <= 0");
}
...您错过了以某种方式或能力设置的keywords
的暴露范围。
由于您的方法是void
,因此您无法断言要从该方法获得的收益。 因此,您必须检查要处理的实体的内部状态。
这可以通过在keywords
字段上使用package-private getter轻松完成:
Set<String> getKeywords() {
return keywords;
}
此时,请确保您的测试类与实际代码位于同一程序包中。
此外,我建议不要在init
中设置这种初始数据。 我认为每个测试都是空白,需要初始化我们要测试的实体。 将实例移动到测试本身内部很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.