java—如何使用mockito测试从数据库中以更新形式获取的对象

csbfibhn  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(369)

在我的应用程序中,我从一个api获取客户的详细信息,并将这个客户保存到数据库中。将此客户对象保存到我的数据库中后,我将返回由数据库生成的id为的客户对象。这是我的rest控制器层,用于从api获取customer对象。

//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));
    }
}

但我不确定这是一种好的测试方法,因为我们没有在服务层中添加任何业务逻辑。那么我该如何测试它以及应该测试哪一层呢。

lvmkulzt

lvmkulzt1#

尝试在集成级别测试这个案例。没有业务逻辑,只有将数据保存到db的纯crud。
你可以用 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

相关问题