当前位置:网站首页>An idea plug-in for automatically generating unit tests
An idea plug-in for automatically generating unit tests
2022-06-23 14:33:00 【Program ape DD_】

source :blog.csdn.net/sun5769675/article/details/111043213
Today, let's introduce a tool Squaretest, It is a plug-in that automatically generates unit tests , Why use it ?
This is mainly because the company has recently adopted the index of code quality control , The HKCEE evaluates the unit test coverage of each project , as well as sonar The problems scanned out , A lot of old projects, old code , Or projects that are in a hurry to deliver , Unit tests are seriously missing , The coverage is only 5% Less than .
So several small partners are doing crazy heap unit tests these days ,3 A pile of people 2 Genius piled up 30%, So I came to help write two , When I wrote the second one, I found , This job shouldn't be done by people , To see the original code , Then write all kinds of... According to the logic Mock, Feeling is something to follow , So I checked , I found that there are plug-ins to help us do this , So let's take a look .
I'm using idea, Let's download the plug-in first ,File——>Settings——>Plugins, Search for Squaretest, then install Just fine , After the plug-in installation is completed, you need to restart

After reboot , There is one more item in the menu bar Squaretest, Now let's talk about how to use , You can also look at the last item of this menu :Generate Test Methods(Help) Let's see a demonstration of it , But the demonstration is not complete , Let me take a screenshot to show you how I use it , And some use experience .

First, we open a class , This class is the one we are going to experiment with , This class has a 7 individual public Method , because Squaretest The generated unit test methods can only generate public Of , Of course, this is also reasonable ! After all private It must be public Called .

If we write the unit test of this class , It takes a while just to see , Let's see how I operate , Open your class , Position the cursor in the code , Right click to select Generate…

Then you will see that there are two familiar icons , For the first time, choose the second option , It will let you choose the template of unit test , Because I have chosen , So I'm not going to pop up again , But I'll tell you how to change the template later .

After selecting the second item, a box will pop up. See below, it will automatically identify the needs of the current class Mock Member variables of , Direct point ok

The real directory hierarchy of the class will be used automatically test Create a unit test class in the folder , The class name is the original class name followed by Test

I'll post the code to show you what it generates , See if it's scary , Bull by bull ,7 Unit test methods , It comes out in seconds , Ladies and gentlemen, how long will it take you to write it yourself , After all, time is money ! Then let's try one !
public class CrawlerScreenShotServiceImplTest {
@Mock
private CrawerScreenShotTaskMapper mockCrawerScreenShotTaskMapper;
@Mock
private CrawerScreenShotTaskLogMapper mockCrawerScreenShotTaskLogMapper;
@InjectMocks
private CrawlerScreenShotServiceImpl crawlerScreenShotServiceImplUnderTest;
@Before
public void setUp() {
initMocks(this);
}
@Test
public void testReceiveData() {
// Setup
final CrawlerScreenShotVO vo = new CrawlerScreenShotVO();
vo.setUrl("url");
vo.setPcFlag(false);
vo.setMembergroup("membergroup");
vo.setTaskType(0);
vo.setUrlType(0);
when(mockCrawerScreenShotTaskLogMapper.saveSelective(any(CrawerScreenShotTaskLog.class))).thenReturn(0);
when(mockCrawerScreenShotTaskMapper.saveBatch(Arrays.asList(new CrawlerScreenShotTask(0L, "url", "imageOssUrl", false, false, "memberGroup", 0, 0, "fileName", new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime(), new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime(), false, "skuCode", "state", "operater")))).thenReturn(0);
// Run the test
final Result<String> result = crawlerScreenShotServiceImplUnderTest.receiveData(vo);
// Verify the results
}
@Test
public void testListJobScreenShotTask() {
// Setup
// Configure CrawerScreenShotTaskMapper.listJobScreenShotTask(...).
final CrawlerScreenShotTaskDto crawlerScreenShotTaskDto = new CrawlerScreenShotTaskDto();
crawlerScreenShotTaskDto.setId(0L);
crawlerScreenShotTaskDto.setUrl("url");
crawlerScreenShotTaskDto.setSkuCode("skuCode");
crawlerScreenShotTaskDto.setPcFlag(false);
crawlerScreenShotTaskDto.setMemberGroup("memberGroup");
crawlerScreenShotTaskDto.setUrlType(0);
crawlerScreenShotTaskDto.setFileName("fileName");
crawlerScreenShotTaskDto.setTaskType(0);
crawlerScreenShotTaskDto.setState("state");
final List<CrawlerScreenShotTaskDto> crawlerScreenShotTaskDtos = Arrays.asList(crawlerScreenShotTaskDto);
when(mockCrawerScreenShotTaskMapper.listJobScreenShotTask(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime())).thenReturn(crawlerScreenShotTaskDtos);
// Run the test
final List<CrawlerScreenShotTaskDto> result = crawlerScreenShotServiceImplUnderTest.listJobScreenShotTask();
// Verify the results
}
@Test
public void testQuery() {
// Setup
final NikeScreenShotListRequestVo requestVo = new NikeScreenShotListRequestVo();
requestVo.setUrl("url");
requestVo.setUrlType(0);
requestVo.setStartTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
requestVo.setEndTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
requestVo.setStatus(0);
requestVo.setPcFlag(0);
requestVo.setPageNum(0);
requestVo.setPageSize(0);
// Configure CrawerScreenShotTaskMapper.query(...).
final PimScreenShotVo pimScreenShotVo = new PimScreenShotVo();
pimScreenShotVo.setId(0L);
pimScreenShotVo.setUrl("url");
pimScreenShotVo.setImageOssUrl("imageOssUrl");
pimScreenShotVo.setStatus(0);
pimScreenShotVo.setPcFlag(false);
pimScreenShotVo.setCreateTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
pimScreenShotVo.setUrlType(0);
pimScreenShotVo.setMsg("msg");
final List<PimScreenShotVo> pimScreenShotVos = Arrays.asList(pimScreenShotVo);
when(mockCrawerScreenShotTaskMapper.query(any(NikeScreenShotListRequestVo.class))).thenReturn(pimScreenShotVos);
// Run the test
final PageInfo<PimScreenShotVo> result = crawlerScreenShotServiceImplUnderTest.query(requestVo);
// Verify the results
}
@Test
public void testQuerySelectBoxData() {
// Setup
// Configure CrawerScreenShotTaskMapper.query(...).
final PimScreenShotVo pimScreenShotVo = new PimScreenShotVo();
pimScreenShotVo.setId(0L);
pimScreenShotVo.setUrl("url");
pimScreenShotVo.setImageOssUrl("imageOssUrl");
pimScreenShotVo.setStatus(0);
pimScreenShotVo.setPcFlag(false);
pimScreenShotVo.setCreateTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
pimScreenShotVo.setUrlType(0);
pimScreenShotVo.setMsg("msg");
final List<PimScreenShotVo> pimScreenShotVos = Arrays.asList(pimScreenShotVo);
when(mockCrawerScreenShotTaskMapper.query(any(NikeScreenShotListRequestVo.class))).thenReturn(pimScreenShotVos);
// Run the test
final PimScreenShotTaskParamsDto result = crawlerScreenShotServiceImplUnderTest.querySelectBoxData();
// Verify the results
}
@Test
public void testFindExecutionScreenShotTaskCount() {
// Setup
when(mockCrawerScreenShotTaskMapper.findExecutionScreenShotTaskCount()).thenReturn(0);
// Run the test
final Integer result = crawlerScreenShotServiceImplUnderTest.findExecutionScreenShotTaskCount();
// Verify the results
assertEquals(0, result);
}
@Test
public void testFindCrawerScreenshotTaskByCreateTime() {
// Setup
final CrawlerScreenShotTaskSyncDto crawlerScreenShotTaskSyncDto = new CrawlerScreenShotTaskSyncDto();
crawlerScreenShotTaskSyncDto.setId(0L);
crawlerScreenShotTaskSyncDto.setUrl("url");
crawlerScreenShotTaskSyncDto.setSkuCode("skuCode");
crawlerScreenShotTaskSyncDto.setTaskType(0);
crawlerScreenShotTaskSyncDto.setStatus(0);
crawlerScreenShotTaskSyncDto.setLastModifyTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
crawlerScreenShotTaskSyncDto.setOperater("operater");
crawlerScreenShotTaskSyncDto.setMsg("msg");
final List<CrawlerScreenShotTaskSyncDto> expectedResult = Arrays.asList(crawlerScreenShotTaskSyncDto);
// Configure CrawerScreenShotTaskMapper.findCrawerScreenshotTaskByCreateTime(...).
final CrawlerScreenShotTaskSyncDto crawlerScreenShotTaskSyncDto1 = new CrawlerScreenShotTaskSyncDto();
crawlerScreenShotTaskSyncDto1.setId(0L);
crawlerScreenShotTaskSyncDto1.setUrl("url");
crawlerScreenShotTaskSyncDto1.setSkuCode("skuCode");
crawlerScreenShotTaskSyncDto1.setTaskType(0);
crawlerScreenShotTaskSyncDto1.setStatus(0);
crawlerScreenShotTaskSyncDto1.setLastModifyTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
crawlerScreenShotTaskSyncDto1.setOperater("operater");
crawlerScreenShotTaskSyncDto1.setMsg("msg");
final List<CrawlerScreenShotTaskSyncDto> crawlerScreenShotTaskSyncDtos = Arrays.asList(crawlerScreenShotTaskSyncDto1);
when(mockCrawerScreenShotTaskMapper.findCrawerScreenshotTaskByCreateTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime())).thenReturn(crawlerScreenShotTaskSyncDtos);
// Run the test
final List<CrawlerScreenShotTaskSyncDto> result = crawlerScreenShotServiceImplUnderTest.findCrawerScreenshotTaskByCreateTime(new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
// Verify the results
assertEquals(expectedResult, result);
}
@Test
public void testQueryCrawlerDashboard() {
// Setup
when(mockCrawerScreenShotTaskMapper.queryCrawlerDashboard(0, 0, 0, new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime(), new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime())).thenReturn(0);
// Run the test
final Integer result = crawlerScreenShotServiceImplUnderTest.queryCrawlerDashboard(0, 0, 0, new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime(), new GregorianCalendar(2019, Calendar.JANUARY, 1).getTime());
// Verify the results
assertEquals(0, result);
}
}Wrong report , Don't panic , This assertion is to check whether the results of your unit test run meet the expectations , If you don't want to check, just want to complete coverage , Just kill it ( Manual formation ).

What about? ! No stimulation , I'm not happy , Seconds seconds 90 Multi line code coverage is reached 90% above .

As mentioned above, the first time you come in will let you choose the template of unit test , If you want to switch, you can press the shortcut key in the unit test class ,Alt+M, Or by Squaretest The penultimate menu , The following is the effect of pressing shortcut keys , I chose this template , You can also learn from .

OK, above Squaretest That's the end of the part , Of course, La can't be happy too early , This class is a relatively successful case , Most of the time, you still have to make minor changes by yourself , After all, the test data it generates may not match your if else Data, right , But it's easy to change , In this way, from their own analysis if else Turned into ,debug The program is complete , Where to report an error ,debug In the past , See if there is a problem with the generated data , Change the data , Passed. , Anyway, I use it very comfortable , Proper savings 70% The amount of work .
After solving the above problem , Found another problem , This tool VO,DTO,Entity,Command,Model In terms of this entity class , Generally, we use this entity class lombok Annotations get,set, also constract Constructor and other annotations , But this tool can only generate unit tests for the constructors of these entity classes , Can't generate get set Unit testing of methods , So I wrote a base Method , Entity class inherits , Simply write two lines of tape , Look at the code below :
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public abstract class BaseVoEntityTest<T> {
protected abstract T getT();
private void testGetAndSet() throws IllegalAccessException, InstantiationException, IntrospectionException,
InvocationTargetException {
T t = getT();
Class modelClass = t.getClass();
Object obj = modelClass.newInstance();
Field[] fields = modelClass.getDeclaredFields();
for (Field f : fields) {
boolean isStatic = Modifier.isStatic(f.getModifiers());
// Filter fields
if (f.getName().equals("isSerialVersionUID") || f.getName().equals("serialVersionUID") || isStatic || f.getGenericType().toString().equals("boolean")
|| f.isSynthetic()) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), modelClass);
Method get = pd.getReadMethod();
Method set = pd.getWriteMethod();
set.invoke(obj, get.invoke(obj));
}
}
@Test
public void getAndSetTest() throws InvocationTargetException, IntrospectionException,
InstantiationException, IllegalAccessException {
this.testGetAndSet();
}
} In the same way, we pass on the entity class Squaretest Generate unit tests , Then inherit the one I wrote above base class ,vo The unit test code of is slightly changed , as follows

see run After that , coverage 100%, Proper , Through these two solutions , In one day, we got coverage 60% above , Don't be too exciting , You can try it , Of course, this is not a unit test written purely for errands , During our follow-up development , You can also use this tool to generate , Then test your code , This is also the way to improve work efficiency !

We have created a high-quality technical exchange group , With good people , I will be excellent myself , hurriedly Click Add group , Enjoy growing up together . in addition , If you want to change jobs recently , Years ago, I spent 2 A wave of large factory classics were collected in a week , Those who are ready to change jobs after the festival can Click here to get !
Recommended reading
00 After rectifying the workplace ?“ In charge of 00 Post department ” Set up the ...
Grafana 9 Official release , Easier to use , Even more cool !
··································
Hello , I'm a procedural ape DD,10 Old driver developed in 、 Alibaba cloud MVP、 Tencent cloud TVP、 I have published books and started a business 、 State-owned enterprises 4 In the Internet 6 year . From ordinary developers to architects 、 Then to the partner . Come all the way , My deepest feeling is that I must keep learning and pay attention to the frontier . As long as you can hold on , Think more 、 Don't complain 、 Do it frequently , It's easy to overtake on a curve ! therefore , Don't ask me what I'm doing now, whether it's in time . If you are optimistic about one thing , It must be persistence to see hope , Instead of sticking to it when you see hope . believe me , Just stick to it , You must be better than now ! If you don't have any direction , You can pay attention to me first , Some cutting-edge information is often shared here , Help you accumulate the capital to overtake on the curve .
边栏推荐
- Wechat applet pop up the optional menu from the bottom
- 分布式数据库使用逻辑卷管理存储之扩容
- Penetration test - right raising topic
- Auto - vérification recommandée! Les bogues MySQL ne font pas reculer les transactions, peut - être êtes - vous à risque!
- Building Intel devcloud
- 微信小程序之flex属性
- 今年英语高考,CMU用重构预训练交出134高分,大幅超越GPT3
- Quick view of wechat applet development process
- Ks003 mall system based on JSP and Servlet
- MATLAB|时序数据中的稀疏辅助信号去噪和模式识别
猜你喜欢

Tencent cloud tdsql-c heavy upgrade, leading the cloud native database market in terms of performance

中国矿大团队,开发集成多尺度深度学习模型,用于 RNA 甲基化位点预测

DTU上报的数据值无法通过腾讯云规则引擎填入腾讯云数据库中

【深入理解TcaplusDB技术】Tmonitor后台一键安装

ICML 2022 | 上下文集成的基于transformer的拍卖设计神经网络

As a software testing practitioner, do you understand your development direction?

如何解决 Iterative 半监督训练 在 ASR 训练中难以落地的问题丨RTC Dev Meetup

知名人脸搜索引擎惹众怒:仅需一张照片,几秒钟把你扒得底裤不剩

微信小程序之从底部弹出可选菜单

加快 yarn install 的三个简单技巧
随机推荐
When pandas met SQL, a powerful tool library was born
Quick view of wechat applet development process
Use of pyqt5 tool box
掌舵9年,艾伦研究所创始CEO光荣退休!他曾预言中国AI将领跑世界
Instructions for laravel8 Beanstalk
Edge and IOT academic resources
期货怎么开户安全吗,期货手续费哪家期货公司比较低,适合散户开户?
ASP. Net C pharmacy management information system (including thesis) graduation project [demonstration video]
3 interview salary negotiation skills, easily win 2K higher than expected salary to apply for a job
Assembly language interrupt and external device operation --06
Test article
vim备份历史命令
What is the working status of software testing with a monthly salary of 7500
The first public available pytorch version alphafold2 is reproduced, and Columbia University is open source openfold, with more than 1000 stars
The second Tencent light · public welfare innovation challenge was launched, and the three competition topics focused on the social value of sustainable development
今年英语高考,CMU用重构预训练交出134高分,大幅超越GPT3
Google Earth engine (GEE) -- Comparative Case Analysis of calculating slope with different methods
Kali use
The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
Do you know which position in the IT industry has the most girls?