What is the point of using Assert.assertNotNull() in frameworks?

Asked

Viewed 275 times

2

I have seen in the Spring Boot framework that they use a lot of Assert.assertNotNull() to validate the variables if they are receiving null values.

It is correct to use this same approach in application development since the goal of using Junit is for unit testing?

  • Not Java manjo, but kick that is to generate an exception and stop the code if you receive null.

  • 2

    It doesn’t make much sense. Java already has the Objects.requireNonNull(). Assert is a Junit class for unit testing, as far as I know, and it’s in that context that it makes sense to use.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

1

Yes, at first it is quite correct, assertions should be standard in every method that one wants robustness. Of course, it may not be, it depends on the goal of the person. It is not right to use anything without understanding it well and is what you really want. You can’t use things on automatic and think you’re right because it works.

For that particular case it would be even better if the language did not accept a null value by default and so the typing itself would take care of it, so whenever the typing solves, a unit test is unnecessary, as if the typing does not solve perhaps an assertion can solve.

If this is done well, it is possible to just do a coverage test to ensure that the code has been tested in all situations and after you have everything in order you can turn off the assertion without incurring processing cost, or if you prefer and it is necessary to leave the verification during execution and to throw an exception when something wrong is passed to the method.

If you want the check to be present in all situations there is not making an assertion and the most correct is a default language check.

Because I don’t work in everyday Java I don’t know if you have better assertion methods than the one used, I don’t even know exactly what this method is since several libraries may have one with the same name, but the assertion is a very valid and useful technique, would like people to use more.

You can understand more in What is the purpose of the "assert()" function and when to use it?.

I imagine I’m talking about unit testing which is the correct term.

  • 1

    Java since version 1.4 has assertions, in case the keyword assert, which is triggered when the feature is explicitly enabled when running the JVM (for reasons of backward compatibility) and the application is compiled in debug mode, that is, it is not triggered in production. I imagine that for these reasons is a resource little known and used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.