2

I read the Oracle recommendations concerning Java's assert and it says that you should use assert for public postconditions, too (http://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html#postconditions).

How would I combine this assert with a automated test, that actually does this check, too?

Example: After invoking the "push" method of a class "Stack" you want to check whether the stack is now not empty. You can use assert and you can use a test.

Is there any best practice, I could do both and the unit test with some more checks, but anyhow I would do things twice, which seems not to be good.

I have already read these questions:

https://softwareengineering.stackexchange.com/questions/18288/are-asserts-or-unit-tests-more-important

assert vs. JUnit Assertions

4

1 回答 1

3

The decision to code assertions is an implementation choice.
The decision to run your JVM with assertions turned on is a runtime choice.

JUnit tests should test behaviour, regardless of implementation or runtime choices.

To be clear, the answer is that your JUnit tests should assert (through code) that the method(s) have the expected outcome. If assertions are in the code that effectively do the same thing, that's irrelevant and should not be relied upon as a justification to not write the corresponding JUnit test, because:

  • the person coding the implementation is quite free to remove the assert statements
  • the JVM may not (ever) run with assertions turned on
于 2013-03-30T13:42:07.273 回答