如何解决如何使用Mockito测试我们从数据库获取更新形式的对象
在我的应用程序中,我正在从API中获取客户详细信息,并将该客户保存到数据库中。将此客户对象保存到我的数据库中之后,我将返回具有数据库生成的ID的客户对象。 这是我剩下的控制器层,用于从API获取客户对象。
//add a new customer and then return all details of newly created customer
@PostMapping("/customer")
public Customer addCustomer(@RequestBody Customer theCustomer)
{
// also just in case they pass an id in JSON ... set id to 0
// this is to force a save of new item ... instead of update
theCustomer.setId(0);
return theCustomerService.saveCustomer(theCustomer);
}
这是我的服务层
@Service
public class CustomerServiceImpl implements CustomerService {
private CustomerDAO theCustomerDAO;
// set up constructor injection
@Autowired
public CustomerServiceImpl(CustomerDAO theCustomerDAO)
{
this.theCustomerDAO=theCustomerDAO;
}
@Override
@Transactional
public Customer saveCustomer(Customer thCustomer) {
return theCustomerDAO.saveCustomer(thCustomer);
}
}
这是我的CustomerDAO层,我将其保存到数据库中
public Customer saveCustomer(Customer theCustomer)
{
// get the current hibernate session
Session currentSession = entityManager.unwrap(Session.class);
//save the customer
currentSession.saveOrUpdate(theCustomer);
return theCustomer;
}
我的应用程序的以上部分正常工作,但是现在我想在其中添加测试。 所以我为服务层创建了一种测试方法。
class CustomerServiceImplTest {
@Test
void saveCustomer() {
CustomerDAO theCustomerDAO=mock(CustomerDAO.class);
CustomerServiceImpl theCustomerServiceImpl=new CustomerServiceImpl(theCustomerDAO);
Customer inCustomer=new Customer("john","nick","google@gmail.com","CPOI939","8607574640");
inCustomer.setId(0);
Customer outCustomer=inCustomer;
outCustomer.setId(9);
when(theCustomerDAO.saveCustomer(inCustomer)).thenReturn(outCustomer);
assertEquals(outCustomer,theCustomerServiceImpl.saveCustomer(inCustomer));
}
}
但是我不确定这是测试的好方法,因为我们没有在服务层中添加任何业务逻辑。 那么我该如何测试以及应该测试哪一层。
解决方法
尝试在集成级别上测试这种情况。没有纯粹的业务逻辑将数据保存到数据库。
您可以使用DbUnit
和诸如H2
之类的内存数据库。
DbUnit是一个JUnit扩展,目标是 数据库驱动的项目,除其他外,这些项目将数据库 在两次测试之间进入已知状态。
示例测试:
@Test
@DatabaseSetup("sampleData.xml")
public void testSaveCustomer() throws Exception {
Customer inCustomer=new Customer("john","nick","google@gmail.com","CPOI939","8607574640");
theCustomerServiceImpl.saveCustomer(inCustomer)
List<Customer> customerList = customerService.findAll();
assertEquals(1,customerList.size());
assertEquals("john",customerList.get(0).getName());
...
}
更多详细信息Spring nad DBUnit
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。