Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Franz Wong
Franz Wong

Posted on

Replace method with JavaParser library

Motivation

Recently I want to migrate from JUnitassertEquals to HamcrestassertThat andis to improve readability of my unit tests.

Instead of using regular expression, it seems it is safer to parse the syntax and manipulate it, so I chooseJavaParser.

Objective

Here is how existing test looks like.

packagecom.franzwong.playground;importorg.junit.jupiter.api.Test;importstaticorg.junit.jupiter.api.Assertions.assertEquals;classMyTest{@Testpublicvoidtest(){Stringa="123";assertEquals("123",a);}}
Enter fullscreen modeExit fullscreen mode

I would like to change it to something like this.

packagecom.franzwong.playground;importorg.junit.jupiter.api.Test;importstaticorg.hamcrest.MatcherAssert.assertThat;importstaticorg.hamcrest.CoreMatchers.is;classMyTest{@Testpublicvoidtest(){Stringa="123";assertThat(a,is("123"));}}
Enter fullscreen modeExit fullscreen mode

Action items:

  1. Remove the static import ofassertEquals
  2. Add static import forassertThat andis
  3. ConvertassertEquals("123", a) toassertThat(a, is("123"))
  4. Save modified source

Solution

Add Maven dependency for JavaParser

<dependency><groupId>com.github.javaparser</groupId><artifactId>javaparser-core</artifactId><version>3.16.2</version></dependency>
Enter fullscreen modeExit fullscreen mode

SetupCompilationUnit

SupposeMyTest.java file is stored in/tmp folder.

SourceRootsourceRoot=newSourceRoot(Path.of("/tmp"));CompilationUnitcu=sourceRoot.parse("","MyTest.java");
Enter fullscreen modeExit fullscreen mode

Remove the static import ofassertEquals

We just need to walk through the syntax tree. If the import declaration node is found and it is theassertEquals node, we just remove it.

cu.walk(ImportDeclaration.class,e->{if(e.isStatic()&&"org.junit.jupiter.api.Assertions.assertEquals".equals(e.getNameAsString())){e.remove();}});
Enter fullscreen modeExit fullscreen mode

Add static import forassertThat andis

Parameters of ImportDeclaration constructor

  • 1st parameter is the static method name
  • 2nd parameter is true if it is a static import
  • 3rd parameter is true if it is asterisk
cu.addImport(newImportDeclaration("org.hamcrest.MatcherAssert.assertThat",true,false));cu.addImport(newImportDeclaration("org.hamcrest.CoreMatchers.is",true,false));
Enter fullscreen modeExit fullscreen mode

ConvertassertEquals("123", a) toassertThat(a, is("123"))

We walk through the syntax tree again. If it is aMethodCallExpr node and its name isassertEquals, we rename it and change its parameters.

cu.walk(MethodCallExpr.class,e->{if(!"assertEquals".equals(e.getNameAsString())){return;}// Rename methode.setName("assertThat");// Get the parameter list of `assertEquals`NodeList<Expression>equalsArgments=e.getArguments();// Create a new `is` method and assign 1st parameter of `assertEquals` to itMethodCallExprisMethod=newMethodCallExpr("is",equalsArgments.get(0));// Change the parametersequalsArgments.set(0,equalsArgments.get(1));equalsArgments.set(1,isMethod);});
Enter fullscreen modeExit fullscreen mode

Save modified source

We just need to provide a folder path to it.

sourceRoot.saveAll(Path.of("/tmp/output"));
Enter fullscreen modeExit fullscreen mode

So that's it. Here is how the whole source code looks like. I hope this tutorial is useful to you.

publicstaticvoidmain(String[]args){SourceRootsourceRoot=newSourceRoot(Path.of("/tmp"));CompilationUnitcu=sourceRoot.parse("","MyTest.java");cu.walk(ImportDeclaration.class,e->{if(e.isStatic()&&"org.junit.jupiter.api.Assertions.assertEquals".equals(e.getNameAsString())){e.remove();}});cu.addImport(newImportDeclaration("org.hamcrest.MatcherAssert.assertThat",true,false));cu.addImport(newImportDeclaration("org.hamcrest.CoreMatchers.is",true,false));cu.walk(MethodCallExpr.class,e->{if(!"assertEquals".equals(e.getNameAsString())){return;}// Rename methode.setName("assertThat");// Get the parameter list of `assertEquals`NodeList<Expression>equalsArgments=e.getArguments();// Create a new `is` method and assign 1st parameter of `assertEquals` to itMethodCallExprisMethod=newMethodCallExpr("is",equalsArgments.get(0));// Change the parametersequalsArgments.set(0,equalsArgments.get(1));equalsArgments.set(1,isMethod);});sourceRoot.saveAll(Path.of("/tmp/output"));}
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Hong Kong
  • Joined

More fromFranz Wong

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp