Spring Framework | Spring unit testing

Spring framework

Benefits of using spring unit testing

There is no need to use ioc.getBean () to get the component any more, directly Autowired component, Spring automatically assembles it.

  • Spring perfectly supports Junit4 (providing a special SpringJunit4ClassRunner) and better supports Testing.
  • On the basis of supporting the original unit testing capabilities, through various listeners, it supports the dependency injection of the test class, access to the Spring applicationContext, and transaction management capabilities, which brings great advantages for the testing of applications using the Spring architecture. Convenience

Steps for usage

1. Guide package: Spring's unit test first needs to import Spring's unit test package.

2. Load file: @ContextConfiguration(locations = "calsspath:applicationContext.xml")

3. Load Spring driver:@RunWith(SpringJUnit4ClassRunner.class)

@RunWith () specifies which driver to use for unit testing. The default is JUnity, which needs to be changed to Spring's own.

Demonstrate the use of Spring unit testing

control layer
public class BookServlet {
private BookService bookservice;
public void doGet() {

Business layer

public class BookService {
private BookDao bookDao;
public void save() {
System.out.println("Calling BookDao to save the book");
Data access layer

public class BookDao {
public void saveBook() {
System.out.println("Book saved successfully");

Use Spring's unit test Test:

  • @ContextConfiguration (locations = "classpath: applicationContext.xml"): Specify the classpath of the configuration file.
  • @RunWith (SpringJUnit4ClassRunner.class): indicates that the Spring driver is used for testing.

@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class iocTest {
BookServlet bookServlet;
public void test01() {

Run the test program to successfully complete the Spring unit test:

Calling BookDao to save the book. Book saved successfully.

Post a Comment

Previous Post Next Post