0

Here is my class. I need to test this parametrized constructor A(String param).

public class A {
    private String superParam;
    private Integer value;

    public A(String param) {
        this();
        append(param);
    }

    public A() {
        this.value = 100; 
    }

    public void append(String additionalParam) {
        this.superParam.concat(additionalParam);
    }        
}

Now I'm struggling with this() invocation. I would be appriciated for any suggestions.

UPD:

I also want to know how can I mock a method during constructor invocation when the object isn't created?

Aaron
  • 1,294
  • 4
  • 14
  • 27

2 Answers2

0

Using a standalone main() method test,

public static void main(String[] args) {
  A a = new A("Hello");
  assert(a.value == 100);
}

I noticed that your code here threw a NullPointerException

this.superParam.concat(additionalParam);

And, while irrelevant to testing the this(), you should assign the result of that operation (which you must do explicitly because Java String(s) are immutable),

this.superParam = this.superParam.concat(additionalParam);

(You might also have changed superParam to a StringBuilder, and concat() to append()). anyway your original version , so I would change

private String superParam;

to

private String superParam = "";

Since the assertion did not fail, and since a.value was not null, the this() constructor was called. Nothing else sets a.value in your code.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • You fixed the `NullPointerException` but the expression still has no effect. It creates a concatenated string and discards it, since it isn't assigned to anything. **Strings are immutable in Java.** (I know you know that.) – David Conrad Jul 07 '14 at 19:24
  • @DavidConrad Good to note. Edited. I also added in the alternative of `StringBuilder`. – Elliott Frisch Jul 07 '14 at 19:28
0

The short answer is that, unless you make value publicly accessible (by changing its access modifier or providing a getter method), you can't test that this() is called.

However, you shouldn't really be checking that this() is called. Your tests should define the behaviour of the class by observing changes in its state, or the changes it makes on other classes, given specific input.

In this situation, you need to ask yourself what becomes different when class A is instantiated with its String param constructor, and that's what you need to check for in your tests. In your example, value isn't used anywhere, but in the actual code that this example comes from, it likely has some influence on the behaviour of the class that you can check on to verify (indirectly) that this() was called. If it doesn't, it's either redundant, or you need to refactor to make your class more testable.

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48