Amazon Interview Question
Quality Assurance EngineersTeam: QAE 1
Country: India
Interview Type: In-Person
An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.
In automation, an assertion refers to a flag which would turn true when a given state is matched.
If by executing a certain piece of code (lets say a function), i expect a certain value to be returned, an assertion would be placed on returned value of function which would turn itself true if a certain output is matched.
Assertions can be very easily turned on or off globally for the running application. Java allows you to enable or disable the checking of assertions during any given runtime context. This is very handy for globally managing assertions as a cross-cutting concern.
You can enable assertions at runtime using -ea switch.
Assertion is used to check the state of a program, test for a condition (mostly pre- and post- and in- conditions). Assert check it and if it does not hold it throws an exception.
- Selmeczy, Péter February 13, 2012The most common way to use it is to add asserts to the beginning and end of methods to check that the state of the object is OK at the beginning and it is OK when ending. But you can use it in loops as well.
These tests are guaranteeing that your algorithm works as it should (see some books on algos that teaches about pre-, post- and maintenance conditions :)