http://my.oschina.net/anomynous/blog/168999
1 引入spring-test
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
2 代码,
注意,sts中SpringJUnit4ClassRunner找不到,不会自动修复,
package com.sgy.service;
import static org.junit.Assert.fail;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.sgy.entity.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class UserServiceTest2 extends AbstractJUnit4SpringContextTests {
@Resource(name="userService") UserService service;
@Test
public void testAdd() {
User user=new User();
user.setUsername("kkk3");
user.setAddTime(new Date());
try {
service.save(user);
System.out.println(user.getId());
} catch (Exception e) {
fail(e.getMessage());
e.printStackTrace();
}finally {
service.delete(user);
}
}
}
3 service层已默认开启事务,如果测试dao层需要开启事务可以加上
@Transactional
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)