简体   繁体   中英

junit test assert, writing test

I am writing test cases for my data array class. For this part, it is okay when the index is between 0 to 30000.

public short value(int index) throws Exception {
    // what block-th buffer
    int block = (index * REC_SIZE) / BLOCK_SIZE;
    int offset = (index * REC_SIZE) % BLOCK_SIZE;

    byte[] curr = bufferPool.getBuffer(block).readBuffer();
    short returnValue = ByteBuffer.wrap(curr)
            .getShort(offset + INDEX_VALUE);

    assert ((returnValue > 0) && (returnValue <= 30000)) : "Invalid"
            + " < Value >: not between 1 to 30000";
    return returnValue;
}

But I also need to test the assert line, which is

assert ((returnValue > 0) && (returnValue <= 30000)) : "Invalid"
        + " < Value >: not between 1 to 30000";

How can I write junit test that I can check when the index is NOT between 0 to 30000?

You can say to the test that you expect an exception to be thrown (since JUnit 4 if I remember well).

@Test (expected = Exception.class)
public void myTest (){
    value(3005);
}

But be careful that assertions can be disable, so I would use an IllegalArgumentException to check the value of your index before any computations and then

 @Test (expected = IllegalArgumentException.class)
 public void myTest (){
     value(3005);
 }

Re-reading your question, I'm not sure if you want to test the value of the index (in which case you could use an IllegalArgumentException ), or the returnValue (in which case you could use a custom exception).

But don't use assert statement for your test cases. assert statements are just for the debug mode of your program. If someone runs it with disabling assertions, you check will not even be tested. So instead throw an Exception (and catch them in your unit tests as I showed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM