Spring 注解方式集成 Junit4 进行单元测试

时间:2022-06-01 20:37:29

通过注解方式实现Spring 集成 Junit4 进行单元测试,因为比部分比较简单,所以直接上代码

  • Maven 依赖
            <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.1.RELEASE</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>4.11</scope>
</dependency>
  • 编写 BaseTest类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContextTest.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public abstract class BaseTest extends TestCase {

}

做好上面两步就可以来时单元测试代码的编写了,如下:

public class MyTest extends BaseTest {

@Autowired
UserDao userDao;

@Test
public void insertTest(){
User user = new User();
user.setName("zhangsan");
user.setAge(13);
UserDao.insert(user );
}

执行单元测试

Spring 注解方式集成 Junit4 进行单元测试