In JUnit, annotations are used to indicate methods that serve specific roles in the testing lifecycle. These annotations help structure the tests and ensure that certain setup and cleanup tasks are performed around your test cases.
- @Before: This annotation marks a method to be run before each test method. It is typically used for setup tasks, such as initializing the WebDriver in Selenium tests.
- @After: This annotation marks a method to be run after each test method. It is used for cleanup tasks, such as closing the browser.
- @Test: This annotation marks a method as a test case. The test method contains the actual code that performs the testing.
- @Ignore: This annotation is used to ignore a test method. This can be useful when a test is not ready to be run or needs to be temporarily disabled.
- @Before Methods: Ensure a clean setup before each test. This prevents tests from affecting each other by resetting the state for each test case.
- @After Methods: Ensure clean up after each test. This is essential for freeing up resources, such as closing browser instances in Selenium tests, to prevent memory leaks and other issues.
- @Test Methods: Define the actual test cases. Each method annotated with @Test is executed as a test, which allows you to write and run individual tests to validate specific functionalities.
- @Ignore Methods: Temporarily disable tests that are not ready or need to be excluded from the test suite. This helps in managing the test suite without deleting test methods that may be needed later.
- Create a Maven Project: Maven helps manage dependencies.
- Add Dependencies: Update pom.xml with the required dependencies.
- Create a new Java class: In src/test/java, create SampleTest.java
.
- Import necessary packages:
- @Test Methods: These methods contain the actual test code. For example, in testGoogleSearch, we navigate to Google, perform a search, and verify the title of the search results page. Each test method should test a single functionality to ensure tests are focused and manageable.
- @After Methods (Teardown): These methods are used for cleanup activities. For instance, in tearDown, we close the browser if it is still open. This ensures that resources are properly released after each test, preventing issues like memory leaks or leftover browser instances. Proper teardown methods are crucial for maintaining a clean and efficient test environment.
- @Ignore Methods: You can annotate a test method with @Ignore to temporarily disable it. This is useful when a test is not ready or needs to be excluded from the current test run. For example:
- Run the test as a JUnit test from your IDE.
- Observe the results to see if the test passes or fails.
- WebDriverWait: Use instead of Thread.sleep for better waiting conditions.
- Browser Drivers: Ensure you have the correct driver installed and configured.