I have a JUnit test class written in spring boot which contains 3 unit tests:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@ContextConfiguration
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class AppclaitionTest {
@BeforeClass
public static void initialize(){
System.out.println(">>>>>>>Intialization Part!");
}
@Test
public void test1(){
System.out.println(">>>>>>>Appcliation Test Started! - Test 1");
Application.main(new String[]{});
System.out.println(">>>>>>>Appcliation Test Ended! - Test 1");
}
@Test
public void test2(){
System.out.println(">>>>>>>Appcliation Test Started! - Test 2");
Application.main(new String[]{});
System.out.println(">>>>>>>Appcliation Test Ended! - Test 2");
}
@Test
public void test3(){
System.out.println(">>>>>>>Appcliation Test Started! - Test 3");
Application.main(new String[]{});
System.out.println(">>>>>>>Appcliation Test Ended! - Test 3");
}
@AfterClass
public static void destory(){
System.out.println(">>>>>>>Destroy Part!");
}
}
If run after the first test, i am getting below the exception:
java.net.BindException: Address already in use: bind
though the application context released, it is not releasing the port number, hence i'm getting the above exception.
Is there any way that I can close the port number before each unit test?
You should consider starting your Spring Boot application by using the SpringApplication class rather than invoking directly the main(String[] args) method of your Spring Boot application that doesn't provide an API to terminate it.
With the SpringApplication way, you could get a ConfigurableApplicationContext instance that provides a way to terminate the running application.
For example :
ConfigurableApplicationContext context;
@Before
public void setup{
SpringApplication springApplication = new SpringApplicationBuilder()
.sources(Application.class)
.build();
context = springApplication.run();
}
@After
public void tearDown(){
SpringApplication.exit(context);
}
@Test
public void test1(){
// action
...
// assertion
...
}
However, you should be cautious about this way of doing.
Starting the Spring Boot application is a relatively expensive operation.
Executing it for any method of test will make slower the tests execution.
Unit tests should be fast.
Integration tests that are executing on a integration machine may be slower.
You should also consider this problematic.
Use @After and @Before to handle before and after calls for each unit test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With