When should I use assert in code, instead of writing a junit test. Are they the same? The question I believe is not specific to java or any particular language
-
Hello, Azzad. Stackoverflow is a place for specific coding issues/problems. Also, this looks like something that could be easily Googled. – Cody May 13 '17 at 04:56
-
2They both work together instead of "instead" – Manish Kumar Sharma May 13 '17 at 04:58
-
Yes, "asserts" in code is good practice. Making a habit of writing JUnit tests for every class is also a good practice. And no, they aren't "the same". They are two very different things, each of which can help you write and maintain better software. – paulsm4 May 13 '17 at 05:04
1 Answers
The java built-in asserts require that the JVM is invoked with a special flag. That reduces their usefulness quite a bit.
You should also understand the differences between testing your product in your test environment versus doing validations within the production environment.
Meaning: you always strive to test all public methods of your classes with unit tests (where you use unit test asserts). You always strive to make your application robust so that it doesn't crash at your customers, but at least gives clear error messages and creates logs for you to debug issues.
But those things are really different aspects of development.
Regarding the comment: JUnit simply provides those many different versions of assert statements for one reason only: expressiveness. Meaning: they help you to write test code that is easy to understand, such as:
assertThat(actualValue, is(expectedValue))
where is()
is a matcher provided by the hamcrest library. If you intend to learn about unit testing: simply remember that you only "need" assertThat()
together with hamcrest matchers.

- 137,827
- 25
- 176
- 248
-
I wanted to ask if that's the reason Junit has a slew of assertThat() API which is not dependent on the JVM ?(I suspect it is...) and if Java assertion had been a mandatory programming construct, Junit would have gone with that? What do you think? – Manish Kumar Sharma May 13 '17 at 05:17
-
Thx for addressing but I do know that. I was wondering about the assert keyword in java and since you said that it requires enabling by JVM, I was wondering if that keyword would make sense in Unit testing libs like Junit after all they have assertThat() APIs instead of keyword. – Manish Kumar Sharma May 13 '17 at 08:34
-
1Again: you dont use the "built-in" assert. Not in production code; not in unit tests. It is that simple. See http://stackoverflow.com/questions/4537609/is-it-a-good-practice-to-use-assert-in-java for example. – GhostCat May 13 '17 at 08:36