Show List

Testing with Spring and JUnit

Spring and JUnit are commonly used together for testing in Java applications.

Spring provides a convenient way to manage dependencies and manage objects in a test environment, while JUnit provides a framework for writing and running tests.

Here's an example of how you can use them together to test a service class:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@SpringBootTest
@SpringJUnitConfig
public class MyServiceTest {

  @Autowired
  private MyService myService;

  @Test
  public void testAdd() {
    int result = myService.add(1, 2);
    assertEquals(3, result);
  }
}

In this example, we use the @SpringBootTest annotation to indicate that we want to load a Spring context, and the @SpringJUnitConfig annotation to configure JUnit with the Spring context.

The @Autowired annotation is used to wire up the MyService instance that we want to test.

Finally, the @Test annotation is used to indicate that the testAdd method is a test method that should be run by JUnit.


    Leave a Comment


  • captcha text