Search code examples
javaunit-testingjunit

Assume vs assert in JUnit tests


I have read that assume will not run the test if assumption failed, but I am not sure regarding the logic of when to place assert vs assume.

For example: any resource loading check should be done with assume?

When should I use assume over assert?

(Note: i am looking for correct design of when to use one over the other)


Solution

  • As you already know, you use assert to fail a test if something goes wrong.

    You use assume if you have circumstances under which a test should not run. "Not run" means that it cannot fail, because, well, it did not run.

    So, in a hypothetical scenario where:

    • you have different builds for different customers, and
    • you have some resource which is only applicable to a particular client, and
    • there is something testable about that resource, then

    you would write a test which:

    • assumes that the resource is present, (so the test will not run on customers that do not have that resource,) and then
    • asserts that everything about the resource is okay (so on the customer that does actually have the resource, the test makes sure that the resource is as it should be.)

    Technically, both assert and assume throw exceptions. The difference is that:

    • the kind of exception thrown by assert will cause the test to fail, while
    • the kind of exception thrown by assume will cause the test to be skipped.