Плагин AspectJ Maven портит классы Groovy, построенные GMaven - PullRequest
1 голос
/ 05 апреля 2011

Я пытаюсь запустить Groovy и AspectJ на модуле, но когда я добавляю AspectJ, классы возвращают очень разные значения, чем я ожидал:

junit.framework.ComparisonFailure: null expected:<2011-04-03> but was:<null>

testGetUnixDayFromDate(com.baselogic.chapter05.utils.DateUtilitiesTest)  Time elapsed: 0.016 sec  <<< FAILURE!
junit.framework.AssertionFailedError: expected:<0> but was:<15037>

testGetDateDifferenceInDays(com.baselogic.chapter05.utils.DateUtilitiesTest)  Time elapsed: 0 sec  <<< FAILURE!
junit.framework.AssertionFailedError: expected:<0> but was:<7>

Это не то, что я ожидал, и когда явыключите AspectJ, все работает нормально.

    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running com.baselogic.chapter05.utils.DateUtilitiesJavaTest
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.422 sec
    Running com.baselogic.chapter05.utils.DateUtilitiesTest
    2011-04-03
    Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.062 sec
    Running com.baselogic.chapter05.utils.StringUtilitiesTest

    Tests run: 26, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.078 sec

    Results :

    Tests run: 30, Failures: 0, Errors: 0, Skipped: 0

    ...

Вот мой плагин AspectJ, который, кажется, вызывает проблему:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.3.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <complianceLevel>1.6</complianceLevel>
            </configuration>
        </plugin>

Но когда я включаю aspectj-maven-plugin все начинает давать сбой:

    [INFO] ------------------------------------------------------------------------
    [INFO] Building Chapter 05: Extending 1.0.2
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ ch05 ---
    [INFO] Deleting C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target
    [INFO]
    [INFO] --- gmaven-plugin:1.3:generateStubs (default) @ ch05 ---
    [INFO] Generated 2 Java stubs
    [INFO]
    [INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ ch05 ---
    [INFO] Using 'UTF-8' encoding to copy filtered resources.
    [INFO] Copying 0 resource
    [INFO]
    [INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ ch05 ---
    [INFO] Compiling 2 source files to C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\classes
    [INFO]
    [INFO] --- maven-scala-plugin:2.15.2:compile (default) @ ch05 ---
    [INFO] Checking for multiple versions of scala
    [INFO] includes = [**/*.scala,**/*.java,]
    [INFO] excludes = []
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\src\main\java:-1: info: compiling
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\generated-sources\groovy-stubs\main:-1: info: compiling
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\src\main\groovy:-1: info: compiling
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\src\main\scala:-1: info: compiling
    [INFO] Compiling 3 source files to C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\classes at 1301955015855
    [INFO] prepare-compile in 0 s
    [INFO] compile in 4 s
    [INFO]
    [INFO] --- gmaven-plugin:1.3:compile (default) @ ch05 ---
    [INFO] Compiled 3 Groovy classes
    [INFO]
    [INFO] --- clojure-maven-plugin:1.3.7:compile (compile-clojure) @ ch05 ---
    [INFO]
    [INFO] --- aspectj-maven-plugin:1.3.1:compile (default) @ ch05 ---
    [INFO]
    [INFO] --- gmaven-plugin:1.3:generateTestStubs (default) @ ch05 ---
    [INFO] Generated 2 Java stubs
    [INFO]
    [INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ ch05 ---
    [INFO] Using 'UTF-8' encoding to copy filtered resources.
    [INFO] Copying 0 resource
    [INFO]
    [INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ ch05 ---
    [INFO] Compiling 3 source files to C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\test-classes
    [INFO]
    [INFO] --- maven-scala-plugin:2.15.2:testCompile (default) @ ch05 ---
    [INFO] Checking for multiple versions of scala
    [INFO] includes = [**/*.scala,**/*.java,]
    [INFO] excludes = []
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\src\test\java:-1: info: compiling
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\generated-sources\groovy-stubs\test:-1: info: compiling
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\src\test\groovy:-1: info: compiling
    [INFO] C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\src\test\scala:-1: info: compiling
    [INFO] Compiling 3 source files to C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\test-classes at 1301955027323
    [INFO] prepare-compile in 0 s
    [INFO] compile in 3 s
    [INFO]
    [INFO] --- gmaven-plugin:1.3:testCompile (default) @ ch05 ---
    [INFO] Compiled 2 Groovy classes
    [INFO]
    [INFO] --- aspectj-maven-plugin:1.3.1:test-compile (default) @ ch05 ---
    [WARNING] No sources found skipping aspectJ compile
    [INFO]
    [INFO] --- maven-surefire-plugin:2.7.1:test (default-test) @ ch05 ---
    [INFO] Surefire report directory: C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\surefire-reports

    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running com.baselogic.chapter05.utils.DateUtilitiesJavaTest
    Apr 4, 2011 6:10:31 PM com.baselogic.chapter05.utils.DateUtilities getYesterdayDate_aroundBody11$advice
    INFO: --------------------
    Apr 4, 2011 6:10:31 PM com.baselogic.chapter05.utils.DateUtilities getYesterdayDate_aroundBody11$advice
    ...
    Tests run: 26, Failures: 21, Errors: 0, Skipped: 0, Time elapsed: 0.093 sec <<< FAILURE!

    Results :

    Failed tests:
      testGetYesterdayDate(com.baselogic.chapter05.utils.DateUtilitiesJavaTest)
    ...

    Tests run: 31, Failures: 26, Errors: 0, Skipped: 0

    [ERROR] There are test failures.

    Please refer to C:\usr\SYNCH\PACKT\3166\Chapters_Code\ch05\target\surefire-reports for the individual test results.

Вот тест Groovy:

    package com.baselogic.chapter05.utils

    import groovy.util.GroovyTestCase
    import java.util.Calendar
    import java.text.SimpleDateFormat

    class DateUtilitiesTest extends GroovyTestCase {
        protected void setUp() {
            super.setUp()
        }

        protected void tearDown() {
            super.tearDown()
        }

        public void testGetYesterdayDate() {
            Calendar calendar = Calendar.getInstance()
            calendar.add(Calendar.DATE, -1)
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd")
            String expected = format.format(calendar.getTime());

            String result = DateUtilities.getYesterdayDate()
            println(result)
            assertEquals(expected, result)
        }

        void testGetUnixDayFromDate() {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.util.Date date = (java.util.Date) formatter.parse("2011-03-03 23:59:59");
            assertEquals(DateUtilities.getUnixDayFromDate(date), 15037);
        }

        void testGetDateDifferenceInDays() {
            java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.util.Date date1 = (java.util.Date) formatter.parse("2011-03-03 23:59:59");
            java.util.Date date2 = (java.util.Date) formatter.parse("2011-03-10 23:59:59");
            assertEquals(DateUtilities.getDateDifferenceInDays(date1, date2), 7);
        }
    }

Затем я также создал пример модульного теста Java:

    package com.baselogic.chapter05.utils;

    import org.junit.Test;

    import static org.junit.Assert.assertEquals;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;

    public class DateUtilitiesJavaTest {

        @Test
        public void testGetYesterdayDate() {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -1);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String expected = format.format(calendar.getTime());

            String result = DateUtilities.getYesterdayDate();
            // Aspect DontWriteToTheConsole will complain:
            // System.out.println(result);
            assertEquals(expected, result);
        }

        @Test
        public void testGetYesterdayDateScala() {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -1);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String expected = format.format(calendar.getTime());

            String result = ScalaDateUtilities.getYesterdayDate();
            assertEquals(expected, result);
        }
    }

Может кто-нибудь помочь мне понять, почему aspectj-maven-plugin , кажется, вызывает ошибки компиляции с моим окончательным байт-кодом?

Ответы [ 2 ]

2 голосов
/ 17 января 2012

Мой опыт работы с GMaven был плохим.Как только я переключился на Gradle, большая часть «странностей» ушлаЭто звучит как странность, которую вы не хотите тратить на GMaven.

0 голосов
/ 24 июля 2015

Я думаю, что переход на Gradle - это не решение, а дорогой обходной путь, особенно для больших проектов. Поэтому я не согласен с Майком Вазовски . Может быть, вам следует просто исправить настройки Maven. Вы можете сделать несколько вещей:

  • Прежде всего, AspectJ Maven 1.3.1 выпущен в 2011 году и использует очень старую версию AspectJ (1.6.10). Почему бы не перейти на AspectJ Maven 1.7, который по умолчанию использует AsepctJ 1.8.2? Вы даже можете обновить его до AspectJ 1.8.6, последней версии, содержащей больше исправлений?

  • Вы также можете рассмотреть вопрос о переходе с GMaven на GMavenPlus, поскольку первый больше не поддерживается AFAIK, а второй -

  • Кстати, вы также можете переключиться с Java 6 на 8 или хотя бы на 7, потому что Java 6 больше не поддерживается.

Моя настройка AspectJ Maven обычно выглядит примерно так (здесь я опускаю настройку GMaven):

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.source-target.version>1.8</java.source-target.version>
    <aspectj.version>1.8.6</aspectj.version>
</properties>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.source-target.version}</source>
                    <target>${java.source-target.version}</target>
                    <!-- IMPORTANT -->
                    <useIncrementalCompilation>false</useIncrementalCompilation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.7</version>
                <configuration>
                    <showWeaveInfo>true</showWeaveInfo>
                    <source>${java.source-target.version}</source>
                    <target>${java.source-target.version}</target>
                    <Xlint>ignore</Xlint>
                    <complianceLevel>${java.source-target.version}</complianceLevel>
                    <encoding>UTF-8</encoding>
                    <verbose>true</verbose>
                </configuration>
                <executions>
                    <execution>
                        <!-- IMPORTANT -->
                        <phase>process-sources</phase>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjtools</artifactId>
                        <version>${aspectj.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </pluginManagement>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
    </dependency>
</dependencies>
...