Reputation: 19
This is the class I'm testing:
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);
}
This is the test for addKeyword method:
@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());
}
Where goes wrong? It can't pass. Thank you for any advice!
And how can I test the Exception in the class cause it doesn't work if I use @Test(expected=Exception.class)
Upvotes: 0
Views: 71
Reputation: 106528
Notwithstanding the fact that you're going to invoke error conditions if you pass null
in, or if the year
is 0 (thanks to this wonderful condition, which may be entirely valid):
if (title == null || title.isEmpty() || year <= 0) {
throw new ListingException("Missing Title or year <= 0");
}
...you're missing the exposure of the keywords
set in some way or capacity.
Since your method is void
, you can't assert against what you're going to get back from the method. So, you have to check the internal state of the entity that you're dealing with.
This is easily accomplished with a package-private getter on the keywords
field:
Set<String> getKeywords() {
return keywords;
}
At that point, be sure that your test class is in the same package as your actual code.
Further, I would advise against setting up that sort of initial data in init
. I'd consider each individual test a blank slate which needs to initialize the entity that we want to test. It'd be a simple matter of moving the instantiation to within the test itself.
Upvotes: 1
Reputation: 3688
You're initializing title
with null
here:
@Before
public void setup() throws Exception {
movieList = new MovieListing(null, 0);
}
And then you're throwing an exception at the constructor if it's null
:
if (title == null || title.isEmpty() || year <= 0) {
throw new ListingException("Missing Title or year <= 0");
}
Upvotes: 1