過去幾天我一直在詮釋/嘲諷地獄。我一直在遇到以下問題:如何在Spring中使用參數實例化和模擬對象
Failed to instantiate [com.test.service.util.Utils]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: value1 cannot be null
我正在寫一個服務類,其中有一個Utils類裏面的模擬測試。這個Utils類依賴於Spring應用程序屬性文件中的值。在我看來,@Value成員被注入爲空。我如何用參數實例化一個對象並在Spring中模擬它?
Service.java看起來是這樣的:
@Service
public class Service {
@Value("${value1}")
private String value1;
private Utils utils = new Utils(value1);
public service_method1() {
utils.utils_method1();
}
}
的utils的類看起來是這樣的:
@Component
public class Utils {
private OtherUtils otherUtils;
public Utils(String value1) {
otherUtils = new OtherUtils(value1);
}
public utils_method1() {
otherUtils.otherUtils_method1()
}
}
ServiceTests.java看起來是這樣的:
public class ServiceTests {
private String VALUE1 = "value1";
@Mock
private Utils utils = new Utils(value1);
@InjectMocks
private Service service;
@Test test_method1() {
//set up mocks for Utils methods
//run Service class methods
}
}
使用'嘗試@ Spy',而不是'@ Mock'在您的測試了'utils'成員變量。 – Jesper
爲快速反應而歡呼,儘管如此,仍然沒有骰子。我刪除了所有@Autowire註釋,是否需要在任何地方使用? – user1077071