Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-6764

Problem Referring To Statically Imported Constants

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.1.9, 2.4.0-rc-1
    • 2.4.8
    • None
    • None

    Description

      It appears that if a class implements an interface which declares constants, Groovy code which statically imports the constant from the class (not the interface) doesn't work. I think this is supposed to work. It does work from Java. See the attached app in constantsquestion.zip which includes the following code. Extract the .zip and run "./gradlew test" to see that the Java test passes and the Groovy test fails.

      src/main/java/com/demo/Constants.java
      package com.demo;
      
      public interface Constants {
          int ANSWER = 42;
      }
      
      src/main/java/com/demo/Helper.java
      package com.demo;
      
      public class Helper implements Constants {
      }
      
      test/java/com/demo/JavaHelperTests.java
      package com.demo;
      
      import org.junit.Test;
      import org.junit.runner.RunWith;
      import org.junit.runners.JUnit4;
      import static org.junit.Assert.assertEquals;
      import static com.demo.Helper.ANSWER;
      
      @RunWith(JUnit4.class)
      public class JavaHelperTests {
      
          @Test
          public void testAccessingConstant() {
              // this test passes...
              assertEquals(42, ANSWER);
          }
      }
      
      test/groovy/com/demo/GroovyHelperSpec.groovy
      package com.demo
      
      import spock.lang.Specification
      import static com.demo.Helper.ANSWER
      
      class GroovyHelperSpec extends Specification {
      
          void 'test referring to statically imported constant'() {
              // this test fails...
              expect:
              42 == ANSWER
          }
      }
      

      The error message from the Groovy spec is:

      groovy.lang.MissingPropertyException: No such property: ANSWER for class: com.demo.GroovyHelperSpec
          at com.demo.GroovyHelperSpec.test referring to statically imported constant(GroovyHelperSpec.groovy:10)
      

      Note that everything works fine from Groovy if the constant is imported from the interface instead of from the class which implements the interface.

      Is this a bug?

      Attachments

        1. constantsquestion.zip
          52 kB
          Jeff Brown

        Issue Links

          Activity

            People

              paulk Paul King
              brownj Jeff Brown
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: