简体   繁体   中英

org.springframework.web.client.ResourceAccessException while mocking POST restTemplate.exchange method in spring boot

I am trying to test a POST request calling in my unit test. I mock the request but I get Connection refuse: connect exception. Here is my code.

My Service 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);
                }
            }
        }
    }
}

Here is my unit test

@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;
    }

}

This is the exception trace which I get.

 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

I have spring boot version 2.3.4 and Java version 11. I have spring-boot-starter-test dependency in my pom.xml file.

I am trying to test a POST request calling in my unit test. I mock the request but I get Connection refuse: connect exception. Here is my code.

My Service 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);
                }
            }
        }
    }
}

Here is my unit test

 @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;
    }

}

This is the exception trace which I get.

 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

I have spring boot version 2.3.4 and Java version 11. I have spring-boot-starter-test dependency in my pom.xml file.

you can remove @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } from both.

And replace @Mock private RestTemplate restTemplate; to become @MockBean private RestTemplate restTemplate;

hope this helps

@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);
            }
        }
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM