Search code examples
eclipsemavenjunitsurefire

Test cases in maven and eclipse


I use maven for managing dependencies in my project. I have seen while writing test cases that some of them pass in eclipse while fail on maven build. I debugged it and found that there are static final members of classes being initialized once retain their values throughout the build. It is a multi-module project.

Is it possible to change the value of those final members for different test cases? Please ask me if you want more clarification. Any links/hints or ideas may be helpful. Thanks.


Solution

  • The static final members are the Java way of expressing constants. First try to modify your test in such a way that it works with the values of these constants. If this is not possible, you can add a second constructor for testing purpose that overrides these values. See the following example:

    Existing code:

    public class SomeClass {
      private static final int LIMIT = 30;
    
      public SomeClass() {
        ...
      }
    
      public void doSomething() {
        ... //the code that uses LIMIT.
      }
    }
    

    Add a second constructor that is used by the test:

    public class SomeClass {
      private static final int DEFAULT_LIMIT = 30;
      private final limit
    
      public SomeClass() {
        this(DEFAULT_LIMIT);
      }
    
      public SomeClass(int limit) {
        this.limit = limit;
        ...
      }
    
      public void doSomething() {
        ... //the code uses limit now.
      }
    }