Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should every test method have at least one assert?

Tags:

unit-testing

When I'm testing a void method there is nothing to assert.For example a CreateSomething method. I know I could call in the test method an other method like FindSomething,but anyway, if there is (in the create method) an error it will show up. So it's a good practice to call an assertion in every method or i'm fine sometimes without an assertion ?

like image 693
user137348 Avatar asked Nov 04 '09 07:11

user137348


People also ask

Should unit tests only have one assert?

I should definitely use only one assert in test method! Using many asserts may be the code smell that you are testing more than one thing. Moreover, there is a chance that somebody can add new assert into your test instead of writing another one.

Why is it recommended to have only one assert statement per test?

“One assertion per test” is a wise rule to keep in mind, because it helps you have tests that fail for a specific reason, and drives you to focus on a specific behavior at a time.

Should you have multiple asserts in one test?

Multiple asserts are good if you are testing more than one property of an object simultaneously. This could happen because you have two or more properties on an object that are related. You should use multiple asserts in this case so that all the tests on that object fail if any one of them fails.

Can you have multiple assertion in a Junit test?

Answer : It is not good to have multiple asserts in a single unit test case. It's better to use only one assert statement in single unit test case.


1 Answers

Not necessarily an Assert

But your test code should do at least one of these:

  • assert that some property/result has/hasn't been set to particular value
  • verify that certain methods have been called/avoided
  • check that exceptions behave (fire or not) as expected

So it's values, actions and errors that you should be checking. Sometimes just one of these, sometimes you can't do it without a combination.

like image 88
Robert Koritnik Avatar answered Nov 14 '22 22:11

Robert Koritnik