2
testLogicalDoc = new LogicalDocumentImpl(-4); assertTrue(testLogicalDoc==null); 

In my code above, I have an assert condition with which I want to make sure I don't create my object with negative size. It is a stringBuilder beneath the covers which throws NegativeArrayBoundsException for a size less than zero. But my junit test fails here. I don't know any other way of making sure an object is not created with a negative size. Any thoughts on how this could be tested ? or should it be a Junit test at all ??

Many thanks,
-Pan
EDIT:

 @Test(expected=NegativeArraySizeException.class) public void testCreate4b() { LogicalDocumentImpl testLogicalDoc = new LogicalDocumentImpl(-4); } 

I'm catching the exception in the LogicalDocumentImpl class but still this test fails with an assertion error but only succeeds when I do a try catch on assertion error ..why is that so ??

3 Answers 3

5

if you are throwing NegativeArrayBoundsException your test case could check like this

@Test(expected= NegativeArrayBoundsException.class) 

That means your test should throw the exception NegativeArrayBoundsException.

Alternatively you can use fail('should never come here for negative values..')

testLogicalDoc = new LogicalDocumentImpl(-4); fail('should never come here for negative values..'); 
Sign up to request clarification or add additional context in comments.

Comments

1

Catch AssertionError and fail otherwise:

try { LogicalDocumentImpl testLogicalDoc = new LogicalDocumentImpl(-4); fail("should throw"); } catch (AssertionError e) { } 

1 Comment

the fail method throws AssertionError (or a subclass named AssertionFailedError in JUnit 3) so this actually doesn't do what it appears to
1

Usually Junit test cases are meant to test that the behavior of your code in certain cases is what you expect. Therefore, for this case you expect that an exception be thrown.

Looking at the JUnit faq (http://junit.sourceforge.net/doc/faq/faq.htm#tests_7) you want to use something like the following:

@Test(expected=NegativeArrayBoundsException.class) 

1 Comment

Will this work if I do a try/catch clause in my method where I create the object ?? or do I need to do a throws only ??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.