0

I have been trying to test a Java client but I keep getting Null Pointer Exception when trying to run the unit test. I cannot tell if it's coming from the test class or the class itself.

This test was working previously, and the only change I added was swapping out the password type from regular String to now an updated type of EncryptedPassword.

I have tried looking through similar questions posted and understanding the difference between primitive types and reference types, but I can't get it to work still.

MenuClient

public class MenuRestClient extends RestClient {
    
    private String host;
    private String username;
    private EncryptedPassword password;

    public MenuRestClient(String host) {
        this.host = host;
        this.username = null;
        this.password = null;
    }

    public MenuRestClient credentials(String user, EncryptedPassword pass) {
        this.username = user;
        this.password = pass;
        return this;
    }
}

MenuClientTest

public class MenuRestClientTest {
    private static String host;
    private static String user;
    private static String pass;

    @BeforeAll
    public static void setup() {
        host = "host";
        user = "user";
        pass = "test123";
    }

    @Test 
    void queryNumberOfItems() throws Exception {
        MenuRestClient client = new MenuRestClient(host).credentials(user, new EncryptedPassword(pass));

        final int items = client.getItems();
        logger.info("Found {} items", items);
    }
}

EncryptedPassword

public class EncryptedPassword {
    
    private String encryptedPass;

    @Autowired
    private PasswordUtil passwordUtil;

    public EncryptedPassword (String encryptedString) {
        encryptedPass = encryptedString;
    }

    public String decrypt() {
        return new String(passwordUtil.convert(new Base64().decode(encryptedPass)), Charsets.UTF_8);
    }
}
BNK
  • 11
  • 1

1 Answers1

0

you have used @Autowired annotation to initialise PasswordUtil.But it seems no where its initialised properly in your test.If you going to follow spring convention use @Autowired with @Component or @Service and Mock your classes accordingly.Or else simply use constructor injection.

indhu
  • 56
  • 5