将变量类型更改为引用类型后,单元测试上的spring Java空指针异常失败
我一直在尝试测试一个Java客户机,但在尝试运行单元测试时,我总是遇到空指针异常。我不知道它是来自测试类还是类本身
这个测试以前是有效的,我添加的唯一更改是将密码类型从常规字符串替换为现在更新的EncryptedPassword类型
我已经试着浏览了发布的类似问题,并理解了基本类型和引用类型之间的区别,但我还是无法让它继续工作
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;
}
}
菜单客户端
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);
}
}
加密密码
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);
}
}
# 1 楼答案
您已使用@Autowired annotation初始化PasswordUtil。但在你的测试中,它似乎没有正确初始化的地方。如果要遵循spring约定,请使用@Autowired with@Component或@Service,并相应地模拟您的类。或者简单地使用构造函数注入