我有以下JUnit测试套件,当我尝试加载我的测试时,我在测试的类中自动装入的依赖项似乎并未加载,并且出现以下错误消息:未加载JUnit依赖关系
package com.uk.jacob.service;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.uk.jacob.model.Ping;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PingerService.class)
@WebAppConfiguration
public class PingerServiceTests {
@Test
public void testPingerServiceReturnsOkWhenServiceIsUp(){
PingerService pingerService = new PingerService();
Ping ping = pingerService.ping("http://devnews.today");
assertEquals(true, ping.ok);
}
@Test
public void testPingerServiceReturnsOkWhenServiceIsDown(){
PingerService pingerService = new PingerService();
Ping ping = pingerService.ping("https://jacob.uk.comz");
assertEquals(false, ping.ok);
}
}
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.uk.jacob.service.PingerService.setHttpAdapter(com.uk.jacob.adapter.HttpAdapter); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.uk.jacob.adapter.HttpAdapter] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
PingerService:
package com.uk.jacob.service;
import java.io.IOException;
import java.net.HttpURLConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.uk.jacob.adapter.HttpAdapter;
import com.uk.jacob.model.Ping;
@Component
public class PingerService {
HttpAdapter httpAdapter;
public Ping ping(String urlToPing) {
Ping ping = new Ping();
try {
HttpURLConnection connection = httpAdapter.createHttpURLConnection(urlToPing);
if(connectionIsOk(connection)){
ping.ok = true;
}
} catch (Exception e) {
ping.ok = false;
}
return ping;
}
private boolean connectionIsOk(HttpURLConnection connection) throws IOException {
return connection.getResponseCode() == 200;
}
@Autowired
public void setHttpAdapter(HttpAdapter httpAdapter){
this.httpAdapter = httpAdapter;
}
}
HttpAdapter:
package com.uk.jacob.adapter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.springframework.stereotype.Component;
@Component
public class HttpAdapter {
public HttpURLConnection createHttpURLConnection(String urlToPing) throws IOException{
URL url = new URL(urlToPing);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
return connection;
}
}
你试过从二传手删除@Autowired,并设置它的属性
一个ComponentScan自动配置? –
并且不要在每个测试中创建一个新的PingService()。为你创建对象句柄Spring。使用@Autowired在Test类中注入PingService并使用它。 –