Spring Framework | Spring unit testing
Spring perfectly supports Junit4 (providing a special SpringJunit4ClassRunner) and better supports Testing. There is no need to use ioc.getBean () to get the component anymore, directly Autowired component, Spring automatically assembles it.
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
@Controller
public class BookServlet {
@Autowired
private BookService bookservice;
public void doGet() {
bookservice.save();
}
}
public class BookServlet {
@Autowired
private BookService bookservice;
public void doGet() {
bookservice.save();
}
}
Business layer
@Service
public class BookService {
@Autowired
private BookDao bookDao;
public void save() {
System.out.println("Calling BookDao to save the book");
bookDao.saveBook();
}
}
public class BookService {
@Autowired
private BookDao bookDao;
public void save() {
System.out.println("Calling BookDao to save the book");
bookDao.saveBook();
}
}
Data access layer
@Repository
public class BookDao {
public void saveBook() {
System.out.println("Book saved successfully");
}
}
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")
@RunWith(SpringJUnit4ClassRunner.class)
public class iocTest {
@Autowired
BookServlet bookServlet;
@Test
public void test01() {
bookServlet.doGet();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
public class iocTest {
@Autowired
BookServlet bookServlet;
@Test
public void test01() {
bookServlet.doGet();
}
}
Run the test program to successfully complete the Spring unit test:
Calling BookDao to save the book. Book saved successfully.
Post a Comment