Gradle Error in contextLoads under test - spring-boot

i am trying to build a web using Spring and Angular Js tegether w/ Gradle. my problem is When i run my project or build gradle this error comes out.
"contextLoads FAILED"
"What went Wrong:"
.> There were failing tests.: /build/reports/tests/test/index.html
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException
ContextLoad Leads me to this Class:
package com.linkedin.learning.linkedinlearningfullstackappangularspringboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class LinkedInLearningFullStackAppAngularSpringBootApplicationTests {
#Test
public void contextLoads() {
}
}
heres the screenshot to make it clearer:
enter image description here

Related

Operation timed out error when running spring-boot:run

I am trying to run through the Spring Quickstart Guide.
I have the DemoApplication.kt file updated to
package com.example.demo
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
#SpringBootApplication
#RestController
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
#GetMapping("/hello")
fun hello(#RequestParam(value = "name", defaultValue = "World") name: String?): String? {
return String.format("Hello %s!", name)
}
When I run ./mvnw spring-boot:run it times out with Exception in thread "main" java.net.ConnectException: Operation timed out.
Stack Trace
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:639)
at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:304)
at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:174)
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:532)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:637)
at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:266)
at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:380)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:193)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1245)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1131)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:179)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1668)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1592)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:224)
at org.apache.maven.wrapper.DefaultDownloader.downloadInternal(DefaultDownloader.java:106)
at org.apache.maven.wrapper.DefaultDownloader.download(DefaultDownloader.java:93)
at org.apache.maven.wrapper.Installer.createDist(Installer.java:86)
at org.apache.maven.wrapper.WrapperExecutor.execute(WrapperExecutor.java:155)
at org.apache.maven.wrapper.MavenWrapperMain.main(MavenWrapperMain.java:72)
Any idea what I need to do differently? Thanks.
The Spring App you wrote wouldn't normally make an outbound connection that could fail - that was what was confusing about the original question.
Now that you have provided the stack trace it is clearer what is going on.
What's happening is that you are compiling and running the app using Maven and Maven needs some more artefacts for your application so it is automatically downloading them for you org.apache.maven.wrapper.DefaultDownloader.download(....
So if you have to use a proxy to reach the Internet, then you need to give these details to Maven. Try this guide: https://maven.apache.org/guides/mini/guide-proxies.html

Run unit tests with spring boot, "no runnable methods" error

I'm running unit tests with Spring boot, but I get a weird no runnable error. The tests pass by the way, but after all test have ended successfully, I get this weird error out of nowhere:
java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:137)
at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
How do I fix this? Why is Spring boot looking for a runnable in my tests?
Here is an example of my code
package ca.bell.uc.hello.world
import org.junit.Assert
import org.junit.jupiter.api.Test
import org.junit.runner.RunWith
import org.springframework.test.context.junit4.SpringRunner
#RunWith(SpringRunner::class)
internal class example {
#Test
fun f() {
Assert.assertTrue(true)
}
}
And here is a screenshot of the error:
Thanks
P.S. This is Kotlin
You are trying to use JUnit 5 #Test annotation because of import:
import org.junit.jupiter.api.Test
In the console log we can see that JUnit 4 is used.
If you want to work with JUnit 4 you should use the import:
import org.junit.Test
Indeed it's the mix of JUnit4 and JUnit5. I had the same thing with tests with #Ignore or #Disabled that would not want to get ignored based on which #Test it was.
You can avoid this issue with spring by updating your spring dependencies and remove the Junit4 dependencies from your build.gradle.kts so that you won't mix them (tested with Gradle v6, check the groovy syntax if you use build.gradle).
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(module = "junit")
exclude(module = "junit-vintage-engine")
exclude(module = "mockito-core")
}
testImplementation("org.junit.jupiter:junit-jupiter:5.4.2")
testImplementation("org.junit.jupiter:junit-jupiter-api")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
Once you have that you don't need to use #RunWith(SpringRunner::class) you can see the difference in your import, they should all contains "jupiter" and your class could look like this:
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
internal class ExampleTest {
#Test
fun test() {
Assertions.assertTrue(true)
}
}

Dropwizard testing - ResourceTestRule throwing NoClassDefFoundError: ch/qos/logback/core/filter/Filter

I am using dropwizard 1.2.4 with log4j 1.2.17. I have followed the instructions as mentioned below
https://github.com/arteam/dropwizard-nologback/
It is throwing the exception like below during unit testing.
java.lang.NoClassDefFoundError: ch/qos/logback/core/filter/Filter
at io.dropwizard.testing.junit.ResourceTestRule.<clinit>(ResourceTestRule.java:34)
at com.vnera.restapilayer.api.resources.ApiInfoControllerTest.<clinit>(ApiInfoControllerTest.java:25)
at sun.misc.Unsafe.ensureClassInitialized(Native Method)
at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:156)
at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1088)
at java.lang.reflect.Field.getFieldAccessor(Field.java:1069)
at java.lang.reflect.Field.get(Field.java:393)
at org.junit.runners.model.FrameworkField.get(FrameworkField.java:73)
at org.junit.runners.model.TestClass.getAnnotatedFieldValues(TestClass.java:230)
at org.junit.runners.ParentRunner.classRules(ParentRunner.java:255)
at org.junit.runners.ParentRunner.withClassRules(ParentRunner.java:244)
at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:194)
at org.junit.runners.ParentRunner.run(ParentRunner.java:362)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: ch.qos.logback.core.filter.Filter
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 19 more
My test code looks like below
import io.dropwizard.testing.junit.ResourceTestRule;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import javax.ws.rs.core.Response;
import static org.mockito.Mockito.mock;
#Category(value = UnitTest.class)
public class ApiInfoControllerTest {
private static ApiNonFunctionalHandler nonFunctionalHandler = mock(ApiNonFunctionalHandler.class);
private static ApiFilter apiFilter = new ApiFilter(nonFunctionalHandler);
private static final String authToken = "NetworkInsight xTyAGJmZ8nU8yJDP7LnA8Q==";
#ClassRule
public static final ResourceTestRule resources = ResourceTestRule.builder()
.addResource(new ApiInfoController())
.addProvider(apiFilter).build();
#Test
public void testApiVersion() throws Exception {
Response response = resources.client()
.target(ApiConstants.INFO_BASE_URL + "/version")
.request()
.header("Authorization", authToken)
.buildGet().invoke();
Assert.assertNotNull(response);
Assert.assertEquals(response.toString(), Response.Status.OK.getStatusCode(), response.getStatus());
final VersionResponse actualError = response.readEntity(VersionResponse.class);
Assert.assertEquals(actualError.getApiVersion(), ApiConstants.API_VERSION);
}
}
My main application is working fine. The configuration.yaml for main application looks like below
# Change default server ports
server:
applicationConnectors:
- type: http
port: 8123
adminConnectors:
- type: http
port: 8124
requestLog:
type: external
logging:
type: external
Can someone let me know what could be going wrong and how can I get around this?
EDIT
Output of mvn dependency:tree is placed here as I am hitting the character limit here.
This is a bug in dropwizard 1.2.4 as discussed below
https://github.com/dropwizard/dropwizard/pull/2338

Am facing this error before starting the application?

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-12 18:47:51.811 ERROR 340 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field leadRepository in com.example.lead.controller.LeadController required a bean of type 'com.example.lead.repo.LeadRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.lead.repo.LeadRepository' in your configuration.
package com.example.lead.repo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
// import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.leadmodel.Lead;
import com.example.leadmodel.LeadEntity;
#Repository
public interface LeadRepository extends JpaRepository<Lead, Integer> {
#Bean
#Autowired
Lead findOne(Integer lead_id);
void save(LeadEntity leadEntity);
}

Spring Cloud Task Scheduling Context Closed

When I run my task without the CommandLineRunner implemented and add the #Scheduled annotation it appears the context is being closed. How can I keep the context open so the #Scheduled can run properly?
DataTransferTask.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DataTransferTask {
public static void main(String[] args) {
SpringApplication.run(DataTransferTask.class, args);
}
}
DataTransferRunner.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
#EnableTask
#EnableScheduling
public class DataTransferRunner {
#Autowired
public DataTransferRunner() {
}
#Scheduled(fixedRateString = "${job_concurrency.fixed-rate}")
public void run() throws Exception {
System.out.println("I started running");
}
}
Here is the exception I keep getting
Caused by: java.lang.IllegalStateException: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#21526f6c has been closed already
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1065) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeanNamesForType(AbstractApplicationContext.java:1176) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.cloud.task.batch.configuration.TaskBatchExecutionListenerBeanPostProcessor.postProcessAfterInitialization(TaskBatchExecutionListenerBeanPostProcessor.java:59) ~[spring-cloud-task-batch-1.2.0.RELEASE.jar:1.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 73 common frames omitted
Since you have #EnableTask, spring will close the context once everything is done running. From the code it looks like you are not running anything explicitly so spring is closing the context before your #Schedule() annotation kicks in.
The fix for that is to tell spring to not close the context at all with spring.cloud.task.closecontext_enable=false. This will keep the context open for your scheduled task.
Some documentation here: https://docs.spring.io/spring-cloud-task/docs/1.2.2.RELEASE/reference/htmlsingle/#features-lifecycle
One more note about the property. In the documentation it says closecontext_enable but after inspecting the logs and the jar, that property has been deprecated and replaced by close_context_enabled.

Resources