[英]Testing @Transactional service method JUnit - without database
I want to write a unit test for a service method which is annotated @Transactional and has calls to Dao layer which creates hibernate criteria based queries.我想为一个带注释的服务方法编写一个单元测试 @Transactional 并调用创建 hibernate 基于条件的查询的 Dao 层。 I am getting the following transaction related exception when the test is executed.执行测试时,我收到以下与事务相关的异常。
org.springframework.transaction.CannotCreateTransactionException
Caused by: javax.persistence.PersistenceException
Caused by: org.hibernate.exception.JDBCConnectionException
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
Caused by: java.net.ConnectException
The test class and service method:测试class及维修方法:
//Service class method
@Transactional(readOnly=true)
public List<Object> fetchSomeData() {
sampleDao.fetchSomeData();
//light weight processing code
//return processed list
}
//Test class
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@ActiveProfiles
public class ServiceTest {
@Autowired
private Service service;
@MockBean
private SampleDao sampleDao;
@Test
public void serviceTest() {
when(sampleDao.fetchSomeData()).thenReturn(new ArrayList<Object>());
List<Object> result = service.fetchSomeData();
//Assert processed data returned
}
}
How to correct this?如何纠正这个?
You can write a unit-test like this:您可以像这样编写单元测试:
@RunWith(MockitoJUnitRunner .class)
public class ServiceTest {
private Service service;
@Before
public void setUp() {
service = new Service();
}
@Mock
private SampleDao sampleDao;
@Test
public void serviceTest() {
when(sampleDao.fetchSomeData()).thenReturn(new ArrayList<Object>());
List<Object> result = service.fetchSomeData();
//Assert processed data returned
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.