当前位置:网站首页>An idea plug-in that automatically generates unit tests, which improves the development efficiency by more than 70%!
An idea plug-in that automatically generates unit tests, which improves the development efficiency by more than 70%!
2022-06-28 12:49:00 【Java technology stack】
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 .
in addition , more IDEA All the plug-ins that are easy to use have been sorted out , WeChat search Java Technology stack , Send it in the background : Tools , You can read it online .
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 !

If you think it's good, use it !
Copyright notice : This paper is about CSDN Blogger 「 Sun Chenbin ( Floating Life )」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement . Link to the original text :https://blog.csdn.net/sun5769675/article/details/111043213
Recent hot article recommends :
1.1,000+ Avenue Java Arrangement of interview questions and answers (2022 The latest version )
2. Explode !Java Xie Cheng is coming ...
3.Spring Boot 2.x course , It's too complete !
4. Don't write about the explosion on the screen , Try decorator mode , This is the elegant way !!
5.《Java Development Manual ( Song Mountain version )》 The latest release , Download it quickly !
I think it's good , Don't forget to like it + Forward !
边栏推荐
- Unity releases webgl and wakes up keyboard input on the mobile terminal inputfield
- Jerry's wif interferes with Bluetooth [chapter]
- Summary of 2022 China Merchants fintech competition
- 杰理之wif 干扰蓝牙【篇】
- 百度APP 基于Pipeline as Code的持续集成实践
- ASP.NET CORE Study08
- 30套JSP网站源代码合集「建议收藏」
- 思源官方付费同步使用指南
- ASP. NET CORE Study08
- It really doesn't matter if a woman fails to pass the college entrance examination and buys thousands of villas in a counter attack
猜你喜欢

Unity Editor Extension Foundation, editorguilayout (III)

ASP. NET CORE Study01

manjaro easyconnecy报错:libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory

Why does CAD export PDF have no color

Ugui uses tips (VI) unity to realize vertical line display of string

The Research Report of Analysys' 2022 China Banking privacy computing platform supplier strength matrix analysis' was officially launched

MySQ 8.0 推出直方图,性能大大提升!

Here comes Wi Fi 7. How strong is it?

What is the difference between internal oscillator, passive crystal oscillator and active crystal oscillator?

Finereport installation tutorial
随机推荐
ASP.NET CORE Study05
Given two points and a point with a middle scale, find the coordinates of the point
多维度监控:智能监控的数据基础
小白创业做电商,选对商城系统很重要!
Jerry's wif interferes with Bluetooth [chapter]
Unity Editor Extension Foundation, editorguilayout (III)
async-validator.js數據校驗器
搭建学习环境
高考失利進哈工大,畢業卻留校要當“探索者”,丁效:科研就是厚積薄發
Flink流处理API大合集:掌握所有flink流处理技术,看这一篇就够了
async-validator.js数据校验器
Siyuan official paid synchronization Guide
Beginner level of attack and defense World Hello_ pwn
几百行代码实现一个 JSON 解析器
IPETRONIK数据采集设备携手Softing Q-Vision软件致力于ADAS测试方案
Summary of 2022 China Merchants fintech competition
运维思考 | 你知道CMDB与监控是什么关系吗?
group_ Concat learning and configuration
It really doesn't matter if a woman fails to pass the college entrance examination and buys thousands of villas in a counter attack
FineReport安装教程