junit 单元测试

1. pom.xml

<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>

2. 建一个BaseTestCase  (这里的classpath是src/main/resource)

@ContextConfiguration(locations = { 
		"classpath:/spring-*.xml",
		"classpath:/spring/**/spring-*.xml",
	
})

@Ignore
@Transactional
public class BaseTestCase extends BaseXXXXTestCase {
	@Resource
	protected UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}

一定要加@Transactional,否则hibernate会报没有transaction

3. 新testcase继承于BaseTeseCase即可

public class UserServiceImplTest extends BaseTestCase {
	
	private static final Logger LOGER = LoggerFactory.getLogger(UserServiceImplTest.class);
	
	@Test
	public void findAllTest() {
		List<User> users = userService.findAll();
		LOGER.info("########## user size: " + users.size());
		assertThat(users.size(), is(20));
	}
}

相关推荐