Can not run Junit in eclipse - spring

I am trying to run spring boot crud example with following code
#SpringBootTest
#RunWith(MockitoJUnitRunner.class)
public class CreateUserServiceTest {
#Mock
private UserRepository userRepository;
#InjectMocks
private CreateUserService createUserService;
#Test
public void whenSaveUser_shouldReturnUser() {
User user = new User();
user.setName("Test Name");
when(userRepository.save(ArgumentMatchers.any(User.class))).thenReturn(user);
User created = createUserService.createNewUser(user);
assertThat(created.getName()).isSameAs(user.getName());
verify(userRepository).save(user);
}
}
But after run it gives bellow error.
"NO test found with test runner 'junit5'"
anyone please help me.
Please check the error message from this file.

Edit: I found the root cause.
JUnit 5 uses annotations from a different package than JUnit 4. When you start a test, Eclipse automatically creates a launch configuration for JUnit 5, but if your annotations are not in the new package, Eclipse would not find the tests and will display the error message.
New annotations:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
// ... other imports from org.junit.jupiter.api
Old annotations:
import org.junit.Test;
// ... imports without "jupiter" in their name
You need to add the following dependencies in a Maven project in order to use JUnit 5:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
Workaround: Use JUnit 4.
You need to select JUnit 4 in your launch configuration. Otherwise this error is shown.
From the main menu select Run -> Run configurations, then select your JUnit test configuration from the navigation bar on the left hand side.

Related

Eclipse - No tests found with test runner 'JUNIT 4'

I have generated a spring boot project from start.spring.io and imported it into STS. The tutorial I'm watching wants to run a JUNIT test before continuing. But when I try to run Junit test I get the following error "No tests found with test runner 'JUNIT 4'.
Also tested with following dependency
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
Any suggestion on how to fix this?
I suspect class DevopsApplicationTests. If I add class DevopsApplicationTests extends TestCase then unit test works but fails. Not sure what should be the correct code.
When testing "import org.junit.Test" I see the following errors.
When trying "import junit.framework.Test;" Also I get "No tests found with test runner 'JUNIT 4' like before but also there is a error near "#Test".
You're using the wrong import.
org.junit.jupiter.api.Test is the annotation for JUnit 5.
For JUnit 4, you need to import junit.framework.Test.
By the way, the latest version of STS is 3.8.0, released in 2017, based on Eclipse Neon from 2016.
STS is deprecated, and is replaced by 'Spring Tools 4 for Eclipse': https://spring.io/tools
Making the class Public fixed the issue.
package com.example.devops;
// import org.junit.jupiter.api.Test;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
public class DevopsApplicationTests {
#Test
public void contextLoads() {
}
}

Spring Boot 2.3.1, JUnit 5, Maven 3.6.3 - Maven lifecycle "test" does not run test suite

pom.xml:
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.7.0-M1</version>
<scope>test</scope>
</dependency>
...
In <build> only is used:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
Not in use in <build> are the plugins maven-surefire-plugin and maven-compiler-plugin
There are a few test classes (MyTest1Test, MyTest2Test, etc.), testing REST controllers. Some test methods are tagged with "myTag", to be included in a test suite, like:
#SpringBootTest
#AutoConfigureMockMvc
public class MyTest1Test {
...
#Test
#WithMockUser
public void test1() {...}
#Test
#WithMockUser
#Tag("myTag")
public void test2() {...}
...
}
Also there is a test suite, defined like:
#RunWith(JUnitPlatform.class)
#SelectClasses({MyTest1Test.class, MyTest3Test.class})
#IncludeTags({"myTag"})
public class MyTestSuiteTest {
...
}
When I select Maven > test, all test classes are run, only the test suite is not run. Why not? What kind of configuration has to be done?
When I run the test suite itself by right-click > Run 'MyTestSuiteTest' within the test class, it is run correctly.
Trying replacing #RunWith(JUnitPlatform.class with #ExtendWith(SpringExtension.class) doesn't solve it. Maven > "test" doesn't run the test suite, and worth, trying to run the test suite with IDE (right-click on the class > Run 'MyTestSuiteTest") shows and error:
org.junit.runners.model.InvalidTestClassError: Invalid test class '...MyTestSuiteTest':
1. No runnable methods
at org.junit.runners.ParentRunner.validate(ParentRunner.java:525)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:102)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:84)
at org.junit.runners.JUnit4.<init>(JUnit4.java:23)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
The IDE tries to run the test suite with JUnit 4, but why? Because of #SelectClasses, #IncludeTags? I have to include the dependency
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.7.0-M1</version>
<scope>test</scope>
</dependency>
to be able to use #SelectClasses and #IncludeTags, but also I excluded the vintage engine. Btw, do I have to remove the exclusion of vintage engine, if running a test suite with #RunWith?
Observation:
Including vintage engine:
Using #RunWith, Maven > "test", shows the following in the console output:
org.junit.vintage.engine.discovery.DefensiveAllDefaultPossibilitiesBuilder$DefensiveAnnotatedBuilder buildRunner
WARNING: Ignoring test class using JUnitPlatform runner: ....MyTestSuiteTest
Running the test suite directly with right-click > Run 'MyTestSuiteTest" via IDE shows an additional entry in the unit test view:
MyTestSuiteTest
JUnit Jupiter
MyTest1Test
test2
MyTest3Test
test1
JUnit Vintage
<no name>
Although there are just two annotated methods to run with the test suite (one from MyTest1Test class, and one from MyTest3Test class), it says 3 test were run successfully. JUnit Vintage didn't show up before when vintage engine was exluded.
Using #ExtendWith with vintage engine included:
Maven > "test" doesn't run the test suite, no warning or similar in the console output. "right-click > Run 'MyTestSuiteTest" gives the reported error.
Excluding vintage engine:
#RunWith behaves as described initially in the question.
#ExtendWith Maven > "test" doesn't run the test suite, no warning or similar in the console output. "right-click > Run 'MyTestSuiteTest" gives the reported error.

Adding spring-cloud-starter-sleuth dependency to a Spring-Boot App some of the Rest Doc test failing

I have a Spring-Boot 2.1.4 application with n-RestDoc tests for Flux controller.
Environment:
Spring-Boot 2.1.4
Junit 5.4.0
spring-restdocs-webtestclient
spring-webflux
If I add the spring-clout-starter-sleuth dependendcy to the app, some of the doc test fails in maven build.
Important on different environment different test classes fails with:
java.lang.IllegalStateException: org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext#6516dd09 has been closed already ....
If run the failling test with maven -Dtest=OptDocTest than the test will not fail, also if a set (not all) test where specified.
Dependendcy
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
<version>2.1.1.RELEASE</version>
<exclusions> <!-- exclude old spring versions -->
<exclusion>
<artifactId>*</artifactId>
<groupId> org.springframework.security</groupId>
</exclusion>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
All test looks simular
#ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
#AutoConfigureRestDocs("target/generated-snippets")
#SpringBootTest(//webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = { ArchimedesApplication.class })
class OptControllerDocTest {
#MockBean
private SrkConnector srkTConnector;
#Autowired
private ApplicationContext context;
private WebTestClient webTestClient;
#BeforeEach
void beforeEach(RestDocumentationContextProvider restDocumentation) {
this.webTestClient = WebTestClient.bindToApplicationContext(context)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
#Test
void documentationTest() throws IOException {
this.webTestClient.post()
.uri("/opt")
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(testRequest))
.exchange()
.expectStatus() // here the error occur
.isOk()
.expectBody() ...
}
All IT Test with a running Boot Application works correct.
I have no idea what goes wrong and why the AnnotationConfigReactiveWebServerApplicationContext is closed.
On a windows box the rest doc test for controller with a flux content fails on a linux box for controller with mono content.
It is solved if I fall back to spring-cloud-starter-sleuth in version 2.1.0.RELEASE and remove all exclusions.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
If I use version 2.1.1.RELEASE the error occur.
This has been raised as a bug in the sleuth github issue list github.com/spring-cloud/spring-cloud-sleuth/issues/1450
If you, as me, have had this situation in regard to junit tests, then I solved it by removing all annotations #DirtiesContext in every junit test class I had in my project.
Same issue I also met. I solved the issue by downgrade Sleuth to 2.0.3.RELEASE(2.1.0 also not work with me). Mine Spring Boot version is 2.0.5.RELEASE.
If 2.0.3 still not work for you, try more downgrade version from mvn repo

error: cannot access BlockJUnit4ClassRunner

While i run the mvn install I'm able to find this above error .
This is my POM.xml i have configured JUnit.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
This is the service Test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class ServiceTestCase {
protected static final Logger LOG = Logger.getLogger(ServiceTestCase.class);
#Configuration
static class AccountServiceTestContextConfiguration {
....
....
....
}
While compiling the above error I am getting.
this Test class I have created in src/test/java
can any one please suggest. How to resolve this ?
When I remove the I am getting error as #Test is not recognise.
Ok, the solution might be quite simple: Update to JUnit 4.5 (or higher).
The javadoc of the BlockJUnit4Runner (which is the Superclass of the SpringJUnit4ClassRunner you are using) states:
#since 4.5
...but as you only use <version>4.4</version>, that's probably the whole problem. Just checked it and the class does simply not exist in JUnit 4.4, so you'll have to upgrade your JUnit version to fix that problem.

Debugger does not stop on breakpoint when using testNG and Surefire

I have added testNG to my pom file and created couple of tests.
#WebAppConfiguration
#ContextConfiguration(classes = {PersistenceConfig.class})
#Transactional
#TransactionConfiguration(defaultRollback = true)
public class TrackPersistenceServiceTest extends AbstractTransactionalTestNGSpringContextTests {
private static Logger logger = LoggerFactory.getLogger(TrackPersistenceServiceTest.class);
#Autowired
TrackPersistenceService trackPersistenceService;
// #Test(groups = {"dev"})
public void thatTracksListCanBeUpdated() throws Exception {
EntitiesCreatedEvent event = trackPersistenceService.updateTracksList();
assertTrue( event.getNumOfCreatedEntities()==12 );
}
When I am running the tests with debug mode using:
call mvn -Dmaven.surefire.debug="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=6666 -Xnoagent -Djava.compiler=NONE" test -Dgroups=dev
The surefire starts and is waiting on port 6666.
The problem: is that though I am connecting to it with intellij remote debugger. It executes the tests but the debugger does not stop at the breakpoints.
I am sure the breakpoints are on code that is being executed.
I added to pom:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.1.1</version>
<scope>test</scope>
</dependency>
Didnt add the surefire plugin to the pom based on this tutorial
Any idea what I am missing?
What I eventually did was to clear the cache.
Though the docs mention File|invalidate cache I could not find and under that menu.
I found it using the find everywhere.
I also update the intellij version.

Resources