我尝试在单元测试中测试一个POST请求调用。我模拟了该请求,但连接被拒绝:连接异常。下面是我的代码。
我的服务类。
@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);
}
}
}
}
}
这是我的单元测试
@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;
}
}
这是我得到的异常跟踪。
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
我有spring Boot 版本2.3.4和Java版本11。我的pom.xml文件中有spring-boot-starter-test依赖项。
2条答案
按热度按时间kupeojn61#
您可以从两者中删除
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }
。并将
@Mock private RestTemplate restTemplate;
替换为@MockBean private RestTemplate restTemplate;
我希望这能有所帮助
2uluyalo2#
@已调度(cron =“${通知.电子邮件.间隔}”)公共void通知电子邮件响应(){
}