_Spring技术–Spring整合Junit
-
首先在pom.xml文件中导入spring-test包:
-
然后再test文件夹下创建测试类,在测试类中需要添加两个注解:
- @RunWith(SpringJunit4ClassRunner.class)
- @ContextConfiguration
-
在测试类中编写测试程序(Spring整合Junit,并且采取纯注解开发)
-
发现问题(待解决):实现数据库表数据的添加和修改时无法成功,也就是只要调用实体类对象的bean的方法会报错,思路是是否需要将实体类的bean配置成非单例的,其余的方法均测试成功
-
package com.Alvis.test.service; import com.Alvis.config.SpringConfig; import com.Alvis.domain.Person; import com.Alvis.service.PersonService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; // 设定类运行器 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringConfig.class) public class PersonServiceTest { // 自动装配PersonService 在Ioc容器中的bean @Autowired private PersonService personService; private Person person; @Test public void selectAll() { // 测试查询数据库表中的全部数据 List<Person> selectAll = personService.selectAll(); System.out.println(selectAll); } @Test public void selectById() { // 测试根据Id查询数据库表中的数据 Person person = personService.selectById(3); System.out.println(person); } // @Test // public void insert() { // // 测试根据在数据库表中添加新的数据 // String name = "老王"; // int age = 34; // String address = "北京"; // // person.setName(name); // person.setAge(age); // person.setAddress(address); // personService.insert(person); // } @Test public void deleteById() { // 测试根据id删除数据库表中的信息 personService.deleteById(5); } // @Test // public void upDateById() { // // 此时通过id名称修改数据库表中的数据 // String name = "老刘"; // int age = 100; // String address = "河南"; // // person.setName(name); // person.setAge(age); // person.setAddress(address); // // personService.Update(person); // } }
-