전문 인터넷 중독자 • 게임 애호가 • 기술 창작자
전문 인터넷 중독자 • 게임 애호가 • 기술 창작자

PMD(코드 분석 도구)를 자동 JUnit 테스트로 실행

PMD(또 다른 훌륭한 정적 코드 분석 도구)를 자동 JUnit 테스트로 실행합니다!
이 페이지는 여러분의 편의를 위해 열정적인 AI 인턴들이 영어에서 번역한 것입니다. 아직 학습 중이므로 몇 가지 오류가 있을 수 있습니다. 가장 정확한 정보는 영어 버전을 참조하세요.
블로그 PMD(코드 분석 도구)를 자동 JUnit 테스트로 실행

이 블로그 게시물은 2011년 2월에 게시되었으므로, 읽는 시점에 따라 일부 내용이 최신이 아닐 수 있습니다. 안타깝게도 정보의 정확성을 보장하기 위해 게시물을 항상 최신 상태로 유지할 수는 없습니다.

    A few months ago, I wrote how it is possible to run Checkstyle as an automatic JUnit test. PMD (don't shoot the messenger!) is another great static code analysis tool. We use both at work to continuously check for smelly code and other code problems.
    So why use both PMD and Checkstyle? Simply because they complement each other in a great way. I usually say that PMD checks what code is written, while Checkstyle checks how the code is written. PMD can check for possible bugs, over complicated methods, duplicated and even unused code.
    Unfortunately, PMD is not as easy to integrate into a JUnit test as we did with Checkstyle. In order run it as an automatic test, we actually had to run it's main method with our arguments and hooking the output streams to capture any error reports.

    Here is an example using Eclipse

    First of all, we download the latest version of PMD (at the current time it would be pmd-bin-4.2.5.zip) and add the pmd-4.2.5.jar, asm-3.1.jar and the jaxen-1.1.1.jar archives (located in the /lib/ folder) as libraries to the Eclipse project. While we are there, we also add the JUnit library as well.
    Properties
    Afterwards, we create a new JUnit test case. The code of the test is below. Please read the code comments for additional information what's being done.
    public class PMDTest { @Test public void testPMDSrc() throws Exception { doPMD("./src/"); } private void doPMD(String sourceFolder) throws Exception { // A friendly message informing we are going to start the test System.out.println("Starting PMD code analyzer test on directory '" + sourceFolder + "'.."); // Init the arguments String filePath = new File(sourceFolder).getAbsoluteFile().toString(); String outputType = "text"; String unusedString = "this is an unsued variable"; String rules = URLDecoder.decode(PMDTest.class.getResource("pmdrules.xml").getFile().toString(), "UTF-8"); String[] arguments = new String[] { filePath, outputType, rules }; // Save the streams to be restored after the test PrintStream out = System.out; PrintStream err = System.err; // Create our new streams to be hooked ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); ByteArrayOutputStream baosErr = new ByteArrayOutputStream(); PrintStream psOut = new PrintStream(baosOut); PrintStream psErr = new PrintStream(baosErr); // Hook the streams with our own System.setOut(psOut); System.setErr(psErr); // Star the actual PMD test PMD.main(arguments); // Restore the default streams System.setOut(out); System.setErr(err); // Close everything up psOut.close(); psErr.close(); baosOut.close(); baosErr.close(); // Organize the output from the PMD test String linesOut[] = baosOut.toString().split("\r?\n"); List rowsOut = new ArrayList(); for (String line : linesOut) { if (line.length() > 0 && line.indexOf("suppressed by Annotation") == -1 && line.indexOf("No problems found!") == -1 && line.indexOf("Error while processing") == -1) { rowsOut.add(line); } } System.out.println("Found " + rowsOut.size() + " errors"); for (String error : rowsOut) { System.out.println(error); } if (baosErr.toString().length() > 0) { System.out.println("Errors:"); System.out.println(baosErr.toString()); } // JUnit asserts Assert.assertTrue(rowsOut.size() + " errors " + rowsOut.toString(), rowsOut.isEmpty()); Assert.assertTrue(baosErr.toString(), baosErr.toString().trim().length() == 0); } }
    Before we can run the test, we need to create an XML file with PMD rules called pmdrules.xml (as specified in the code above). Below is an example of such a file. You can create your own set of rules to specify what checks you would like to perform. Here is the set of rules we are using in this example.
    <?xml version="1.0"?> <ruleset name="customruleset"> <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/> </ruleset>
    Now we can run our test.
    JUnit results
    Oh, look - PMD found an unused varible in my code. How clumsy of me ;-)

    Special Agent Squeaky님이 작성했습니다. 최초 게시일 2011년 2월 5일. 최종 업데이트일 2011년 2월 5일.

    📺 스퀴키의 최신 영상을 시청하세요!

    라이브 스트림에 간단한 실시간 자막을 추가하는 방법