Java 在spring boot中模拟POST restTemplate.exchange方法时发生org.springframework.web.client.ResourceAccessException
我试图在单元测试中测试POST请求调用。我模拟了这个请求,但是我得到了连接拒绝:connectexception。这是我的密码 我的服务班Java 在spring boot中模拟POST restTemplate.exchange方法时发生org.springframework.web.client.ResourceAccessException,java,spring,spring-boot,unit-testing,Java,Spring,Spring Boot,Unit Testing,我试图在单元测试中测试POST请求调用。我模拟了这个请求,但是我得到了连接拒绝:connectexception。这是我的密码 我的服务班 @Service public class NotifiyEmailServiceImpl implements NotifiyEmailService{ private static final Logger logger = LoggerFactory.getLogger(NotifiyEmailServiceImpl.class);
@Service
public class NotifiyEmailServiceImpl implements NotifiyEmailService{
private static final Logger logger = LoggerFactory.getLogger(NotifiyEmailServiceImpl.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private EmailService emailService;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Scheduled(cron = "${notify.email.interval}")
public void notifyEmailResponse () {
logger.info("notifyEmailResponse() begin");
List<Email> emails = emailService.getUnNotifiedEmails();
logger.info("Total (" + emails.size() + ") unnotified emails found!");
for (Email email : emails) {
HttpEntity<Notify> requestEntity = new HttpEntity<>(new Notify(email.getId(), email.getReqStatus()));
logger.info("going to notify response against id=" + email.getId());
ResponseEntity<NotifyResponse> responseEntity = restTemplate.exchange(email.getNotifyUrl()
, HttpMethod.POST, requestEntity, NotifyResponse.class);
logger.info("Response statusCode = " + responseEntity.getStatusCode());
NotifyResponse response = responseEntity.getBody();
if(response != null) {
if(response.getSuccess() == true) {
logger.info("notification submitted successfully!");
email.setAckStatus(1);
emailService.save(email);
logger.info("updated status=" + 1);
} else {
logger.info("unable to notify");
email.setAckStatus(2);
emailService.save(email);
logger.info("updated status=" + 2);
}
}
}
}
}
@服务
公共类NotifiyEmailServiceImpl实现NotifiyEmailService{
私有静态最终记录器Logger=LoggerFactory.getLogger(NotifiyEmailServiceImpl.class);
@自动连线
私有RestTemplate RestTemplate;
@自动连线
私人电邮服务;
@豆子
公共RestTemplate RestTemplate(){
返回新的RestTemplate();
}
@已计划(cron=“${notify.email.interval}”)
public void notifyEmailResponse(){
info(“notifyEmailResponse()begin”);
列出电子邮件=emailService.getUnNotifiedEmails();
logger.info(“找到未通知的电子邮件总数(“+emails.size()+”));
(电邮:电邮){
HttpEntity requestEntity=newhttpentity(newnotify(email.getId(),email.getReqStatus());
logger.info(“将根据id=“+email.getId())通知响应”;
ResponseEntity ResponseEntity=restTemplate.exchange(email.getNotifyUrl())
,HttpMethod.POST,requestEntity,NotifyResponse.class);
logger.info(“Response statusCode=“+responseEntity.getStatusCode());
NotifyResponse=responseEntity.getBody();
if(响应!=null){
if(response.getSuccess()==true){
logger.info(“通知已成功提交!”);
email.setAckStatus(1);
emailService.save(电子邮件);
logger.info(“更新状态=”+1);
}否则{
logger.info(“无法通知”);
email.setAckStatus(2);
emailService.save(电子邮件);
logger.info(“更新状态=”+2);
}
}
}
}
}
这是我的单元测试
@SpringBootTest
public class NotifiyEmailServiceTest {
@Autowired
private EmailService emailService;
@MockBean
private IEmailRepository emailRepository;
@Mock
private RestTemplate restTemplate;
@Autowired
NotifiyEmailServiceImpl notifyEmailService;
@Bean
public RestTemplate RestTemplate(){
return new RestTemplate();
}
@Test
public void notifyEmailStatus() {
String url = "http://localhost:8081/api/v1/emails/notifyResponse";
List<Email> emails = getSampleEmails();
when(emailRepository.findByAckStatusAndNotifyUrl()).thenReturn(emails);
HttpEntity<Notify> requestEntity = new HttpEntity<>(new Notify((long)1, 1));
NotifyResponse response = new NotifyResponse(true, "success");
when(restTemplate.exchange(url, HttpMethod.POST, requestEntity, NotifyResponse.class))
.thenReturn(new ResponseEntity<NotifyResponse>(response, HttpStatus.OK));
List<Email> emailsRes = emailService.getUnNotifiedEmails();
notifyEmailService.notifyEmailResponse();
assertEquals(2, emailsRes.size());
assertEquals(true, response.getSuccess());
}
public List<Email> getSampleEmails(){
List<Email> emails = new ArrayList<Email>();
Email email1 = new Email();
email1.setEmailFrom("emailfrom@myemail.com");
email1.setEmailTo("emailto@myemail.com");
email1.setNotifyUrl("http://localhost:8081/api/v1/emails/notifyResponse");
email1.setEmailSubject("subject");
email1.setReqStatus(0);
Email email2 = new Email();
email2.setEmailFrom("emailfrom@myemail.com");
email2.setEmailTo("emailto@myemail.com");
email2.setNotifyUrl("http://localhost:8081/api/v1/emails/notifyResponse");
email2.setEmailSubject("subject");
email2.setReqStatus(0);
emails.add(email1);
emails.add(email2);
return emails;
}
}
@SpringBootTest
公共类NotifiyEmailServiceTest{
@自动连线
私人电邮服务;
@蚕豆
私人IEmailRepository-emailRepository;
@嘲弄
私有RestTemplate RestTemplate;
@自动连线
NotifiyEmailServiceImpl notifyEmailService;
@豆子
公共RestTemplate RestTemplate(){
返回新的RestTemplate();
}
@试验
public void notifyEmailStatus(){
字符串url=”http://localhost:8081/api/v1/emails/notifyResponse";
列出电子邮件=getSampleEmails();
当(emailRepository.findByAckStatusAndNotifyUrl())。然后返回(电子邮件);
HttpEntity requestEntity=新的HttpEntity(新通知((长)1,1));
NotifyResponse=新NotifyResponse(真,“成功”);
何时(restemplate.exchange(url、HttpMethod.POST、requestEntity、NotifyResponse.class))
.然后返回(新的ResponseEntity(response,HttpStatus.OK));
List emailsRes=emailService.getUnNotifiedEmails();
notifyEmailService.notifyEmailResponse();
assertEquals(2个,emailsRes.size());
assertEquals(true,response.getSuccess());
}
公共列表getSampleEmails(){
列出电子邮件=新建ArrayList();
Email email1=新电子邮件();
email1.setEmailFrom(“emailfrom@myemail.com");
email1.setEmailTo(“emailto@myemail.com");
email1.setNotifyUrl(“http://localhost:8081/api/v1/emails/notifyResponse");
email1.设置EmailSubject(“subject”);
email1.setReqStatus(0);
Email email2=新电子邮件();
email2.setEmailFrom(“emailfrom@myemail.com");
email2.setEmailTo(“emailto@myemail.com");
email2.setNotifyUrl(“http://localhost:8081/api/v1/emails/notifyResponse");
email2.设置EmailSubject(“subject”);
email2.setReqStatus(0);
emails.add(email1);
emails.add(email2);
回复邮件;
}
}
这是我得到的异常跟踪
org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://localhost:8081/api/v1/emails/notifyResponse": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:748)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:583)
at com.ivt.email.services.impl.NotifiyEmailServiceImpl.notifyEmailResponse(NotifiyEmailServiceImpl.java:55)
at com.ivt.email.services.NotifiyEmailServiceTest.notifyEmailStatus(NotifiyEmailServiceTest.java:71)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:141)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:503)
at java.base/sun.nio.ch.Net.connect(Net.java:492)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
at java.base/java.net.Socket.connect(Socket.java:648)
at java.base/java.net.Socket.connect(Socket.java:597)
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:341)
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:362)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1261)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1194)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1082)
at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1016)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:739)
... 69 more
org.springframework.web.client.ResourceAccessException:POST请求的I/O错误“http://localhost:8081/api/v1/emails/notifyResponse“:连接被拒绝:连接;嵌套异常为java.net.ConnectException:拒绝连接:连接
位于org.springframework.web.client.restemplate.doExecute(restemplate.java:748)
位于org.springframework.web.client.restemplate.execute(restemplate.java:674)
位于org.springframework.web.client.restemplate.exchange(restemplate.java:583)
位于com.ivt.email.services.impl.NotifiyEmailServiceImpl.notifyEmailResponse(NotifiyEmailServiceImpl.java:55)
位于com.ivt.email.services.NotifiyEmailServiceTest.notifyEmailStatus(NotifiyEmailServiceTest.java:71)
位于java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
位于java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
位于java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
位于java.base/java.lang.reflect.Method.invoke(Method.java:564)
位于org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
位于org.junit.jupiter.engine.execution.MethodInvocation.procedure(MethodInvocation.java:60)
位于org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.Procedue(InvocationInterceptorChain.java:131)
位于org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
位于org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
位于org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
位于org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0