Search code examples
javajunit4

How to test private field is set to supplied value using public method in JUnit?


I have a class:

public class MyEncryptor {

    private StringEncryptor stringEncryptor; // this is an interface ref

    public void setStringEncryptor(StringEncryptor stringEncryptorImpl) {

        if(condition){
            this.stringEncryptor = stringEncryptorImpl;
        }

    }
}

When Testing in JUnit for method setStringEncryptor, i want to test if instance value stringEncryptor is set to what i've supplied in parameter as implementation? or i'm going the wrong way for testing this method?

Below is my failed attempt in a junit test method:

MyEncryptor decryptor = new MyEncryptor ();

        StringEncryptor spbe = new StandardPBEStringEncryptor();
        decryptor.setStringEncryptor(spbe);

        Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
        f.setAccessible(true);

        Assert.assertSame(f, spbe);

I want to test that stringEnctyptor is set to spbe in junit


Solution

  • Here you assert that the java.lang.reflect.Field stringEncryptor is the same object than the StringEncryptor object you create for your test :

    StringEncryptor spbe = new StandardPBEStringEncryptor();
    ...
    Field f = MyEncryptor .class.getDeclaredField("stringEncryptor");
    f.setAccessible(true);
    Assert.assertSame(f, spbe);
    

    These are two distinct objects of two distinct and no related classes.
    You should first retrieve the value associated to the field :

     Object value = f.get(spbe);
    

    and then compare the objects :

    Assert.assertSame(value, spbe);
    

    But anyway I don't think it is the good way.
    To test a code, the implementation should be testable.
    Doing reflection to test the code should be done only if we have really not the choice.
    A natural way to test your code is providing a method to get the actual StringEncryptor field.

    public StringEncryptor getStringEncryptor(){
         return stringEncryptor;
    }
    

    In this way you could assert the field value in a straight way.