我正在尝试使用junit测试来测试我的服务层。除插入外,每件事都按预期工作。
这是我的用于插入的配置测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-servlet.xml"})
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
public class TestUserAccountDao {
@Autowired
UserAccountService userManager;
UserAccount newUser;
@Before
public void init() {
newUser = new UserAccount();
newUser.setUsername("TestUser");
newUser.setEmail("testEmail@gmail.com");
newUser.setPassword("123456");
}
@After
public void tearDown() {
//userManager.remove(newUser);
newUser = null;
}
/** test: void add(UserAccount)
* */
@Test //@Transactional
public void testAdd() {
System.out.println(newUser);
userManager.add(newUser);
/*Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(newUser);
session.getTransaction().commit();
session.close();*/
}
当我涉及userManager.add(newUser)时,我遇到的问题是UserAccount不会持久存储到数据库中。但是,如果我切换到使用纪念会话,它的工作完美。我不认为我的spring-servlet.xml有任何问题,因为我可以成功测试其他方法,而且我没有做任何复杂的add(),只是session.save(UserAccount)。
这是我得到的堆栈跟踪:
INFO | 2014-09-05 10:12:43,268 | TransactionalTestExecutionListener.java | 298 | Rolled back transaction after test execution for test context [DefaultTestContext@44d46936 testClass = TestUserAccountDao, testInstance = com.isad.test.dao.TestUserAccountDao@55477b87, testMethod = testValidateLoginByName@TestUserAccountDao, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@47ff07ce testClass = TestUserAccountDao, locations = '{classpath:spring-servlet.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
INFO | 2014-09-05 10:12:43,271 | TransactionalTestExecutionListener.java | 276 | Began transaction (2) for test context [DefaultTestContext@44d46936 testClass = TestUserAccountDao, testInstance = com.isad.test.dao.TestUserAccountDao@2dda03f0, testMethod = testValidateLoginByEmail@TestUserAccountDao, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@47ff07ce testClass = TestUserAccountDao, locations = '{classpath:spring-servlet.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.hibernate4.HibernateTransactionManager@38598a4f]; rollback [true]
答案 0 :(得分:0)
事务通常由服务层管理(在您的情况下,对服务方法使用Spring @Transactional
注释)。因此,当您测试它时,您不必使用事务(您不必打开和关闭它)。
如果你想对你的服务层进行单元测试,你将不得不用Mockito来模拟你的DAO(persitance层)。