![](/img/trans.png)
[英]How to Mock an object which is created in the class under test in Mockito
[英]How to use mockito to test an object which we are getting in updated form from database
在我的應用程序中,我從 API 獲取客戶詳細信息並將該客戶保存到數據庫中。 將此客戶 object 保存到我的數據庫后,我返回客戶 object,其 ID 由數據庫生成。 這是我的 rest Controller 層,用於從 API 獲取客戶 object。
//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));
}
}
但我不確定這是一個好的測試方法,因為我們沒有在服務層添加任何業務邏輯。 那么我該如何測試它以及應該測試哪一層。
嘗試在集成級別測試此案例。 沒有業務邏輯只是純粹的 crud 將數據保存到數據庫。
您可以使用DbUnit
和H2
等內存數據庫。
DbUnit 是一個針對數據庫驅動項目的 JUnit 擴展,除其他外,它將您的數據庫放入測試運行之間的已知 state 中。
示例測試:
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.