在平常的工作中,我们经常会用到单元测试,那么,单元测试应该怎么写呢?有什么需要注意的地方呢?

比如保存,数据是否保存成功,我们应该用单元测试怎么断言呢?像保存完成后,再去数据库做一边查询,看数据是否保存成功,那么,除过这种,我们还可以用下面的这种方式.

1:引入包:

junitjunit4.12testorg.mockitomockito-all2.0.2-betatestorg.powermockpowermock-api-mockito22.0.9testorg.powermockpowermock-module-junit42.0.0test

2:service保存方法:

package test.boot.service.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import test.boot.dao.StudentDao;import test.boot.service.StudentService;import test.boot.vo.StuentVO;@Servicepublic class StudentServiceImpl implements StudentService {@Autowiredprivate StudentDao studentDao;public void save(StuentVO vo1) {studentDao.save(vo1);}}

3:单元测试:

import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.mockito.ArgumentCaptor;import org.mockito.Mock;import org.powermock.api.mockito.PowerMockito;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import test.boot.SpringbootApplicationTest;import test.boot.dao.StudentDao;import test.boot.service.StudentService;import test.boot.vo.StuentVO;import static org.mockito.Mockito.verify;@RunWith(SpringRunner.class)@SpringBootTest(classes = SpringbootApplicationTest.class)public class StudentTest {@Mockprivate StudentDao studentDao;@Mockprivate StudentService studentService;@Testpublic void test02(){StuentVO vo = new StuentVO();vo.setName("大杜");vo.setPhone("12345678911");vo.setId(1L);// 先调用保存方法studentService.save(vo);// 对入参进行获取ArgumentCaptor stuentVOArgumentCaptor = ArgumentCaptor.forClass(StuentVO.class);verify(studentDao).save(stuentVOArgumentCaptor.capture());Assert.assertEquals("姓名不一致", vo.getName(), stuentVOArgumentCaptor.getValue().getName());}}

4:像保存这些接口,无返回值,但是需要进行断言,看是否保存成功,我们mock保存方法,这样可以进行判断。

不断的学习,不断的充实自己,生活才会更加的美好!2024加油!美好的风景一直在路上!