我是JUnit的新手并尝试测试使用JPA DAO的spring Web服务。我需要测试类似于下面的服务方法。
使用@Transactional(propagation=Propagation.REQUIRED)
注释服务方法,ServiceObjectRepository.update()
方法调用本机sql查询来更新数据库。
@Transactional(propagation=Propagation.REQUIRED)
public void serviceMethod(){
//Read DB for ServiceObject to update
//Call ServiceObjectRepository.update() method to update DB
}
ServiceObjectRepository
public interface ServiceObjectRepository extends JpaRepository<ServiceObject, Integer> {
@Query(value ="UPDATE serviceobjcet AS c SET c.objectstatus= :os WHERE c.objid = :oi", nativeQuery = true)
public Integer update(@Param("os")short objStatus,@Param("oi")int objId);
}
识别TestClass
@TransactionConfiguration(defaultRollback=true)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = "classpath:service-test.xml")
@Transactional
public class ServiceHandlerTest {
@Test
public void testServiceMethod() {
//Create ServiceObject and save to DB
//Call serviceMethod()
//Read DB for updatedServiceObject
assertEquals("Test: Object should be in updated state", new Short(3), updatedServiceObject.getObjectstatus(), 0);
}
}
我的测试运行并回滚数据库事务。但问题是当我在调用updatedServiceObject
后读取serviceMethod
时它没有返回更新的对象。所以我的测试失败了assertEquals
的NullPointerException。有没有想过克服这个问题?
答案 0 :(得分:2)
最后,我提出了一个解决方案,而不是在测试方法中创建ServiceObject
并保存到DB,而是在测试方法之前完成它并在事务之后删除创建的对象。所以我的测试类看起来像,
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:service-test.xml")
public class ServiceHandlerTest {
@Before
public void setup() {
//Create ServiceObject and save to DB
}
@Test
public void testServiceMethod() {
//Call serviceMethod()
//Read DB for updatedServiceObject
assertEquals("Test: Object should be in updated state", new Short(3), updatedServiceObject.getObjectstatus(), 0);
}
@After
public void teardown() {
//Delete created ServiceObject from DB
}
}
我发现测试方法或测试类在这种情况下不需要是事务性的。