我在我的应用程序中使用JUnit4,我试图测试UserService
,目前的测试用例很简单:
Create a user named 'admin' and save it to the database.
The other test case will rely on this user.
所以我使用BeforeClass
来插入记录,但是我必须使用UserService
来保存用户,但是spring不支持注入静态字段。
当我尝试手动创建UserService
时,我发现自己必须填写依赖项,我想知道是否有替代方案?或者我如何使用JUnit有什么问题?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/application-config.xml"})
public class UserServiceTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Autowired
private UserService userService;
//@Autowired // sprint does not suport this
private static UserService us;
private static User u;
@BeforeClass
public static void before() {
us = new UserServiceImpl(); // this UserService instance can not be used, since I have to fill the dependencies manually
us.clear();
u = new User();
u.setUsername("admin");
u.setPassword("pass");
us.save(u);
}
@AfterClass
public static void after() {
userService.delete(u.getId());
}
@Test
public void testQuery() {
List<User> list = userService.find();
assertEquals(1, list.size());
}
@Test
public void testChangePassword() {
userService.changePassword(u.getId(), u.getPassword(), "newpass");
assertEquals("newpass", userService.findOne(u.getId()).getPassword());
exception.expect(ResourceNotFoundException.class);
userService.changePassword("1", "32", "ss");
exception.expect(ResourceNotFoundException.class);
userService.changePassword(u.getId(), "32", "ss");
}
}