在平常工作,经常会用到单元测试,那么单元测试应该怎么写呢?
1:引入包:
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.mockito</groupId><artifactId>mockito-all</artifactId><version>2.0.2-beta</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-api-mockito2</artifactId><version>2.0.9</version><scope>test</scope></dependency><dependency><groupId>org.powermock</groupId><artifactId>powermock-module-junit4</artifactId><version>2.0.0</version><scope>test</scope></dependency>
2:service:
@Service
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentDao studentDao;public StuentVO queryById(Long id) {return studentDao.queryById(id);}
}
3:单元测试:
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
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.service.StudentService;
import test.boot.vo.StuentVO;@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplicationTest.class)
public class StudentTest {@Mockprivate StudentService studentService;@Testpublic void test01(){StuentVO vo = new StuentVO();vo.setName("大杜");vo.setPhone("12345678911");vo.setId(1L);PowerMockito.when(studentService.queryById(1L)).thenReturn(vo);StuentVO queryVO = studentService.queryById(1L);Assert.assertEquals("姓名不一致", vo.getName(), queryVO.getName());}
}
4:运行结果:
5:使用Mock,比如有些数据依赖数据库查询,如果数据库数据更改,可能会使单元测试报错;或者方法依赖于其他系统的接口等,如果需要完成单元测试,那么mock一个对应的类以及应该返回的值。
风景很美,生活,一直在路上!2024,新的一年,加油!