I am following this tutorial:
https://www.baeldung.com/spring-boot-embedded-mongodb
Only dot 1,2,3
I need insert and check new registers in my mongoDB embebed.
this is my pom:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.1.1.RELEASE</version><!--$NO-MVN-MAN-VER$ -->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
It is my test.java:
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.batch.DesarrolloBatch.model.Documento;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;
#DataMongoTest
public class TestApplicationConfiguration {
#Test
public void test(#Autowired MongoTemplate mongoTemplate) {
// given
DBObject objectToSave = BasicDBObjectBuilder.start()
.add("_id", "999999999999")
.get();
// when
mongoTemplate.save(objectToSave, "collection");
List<Documento> list = mongoTemplate.findAll(Documento.class, "collection");
System.out.println("size " + list.size());
// then
assertThat(mongoTemplate.findAll(Documento.class, "collection")).extracting("_id")
.containsOnly("999999999999");
}
}
I am trying insert a new Documento with attribute _id value= 99999999
But this code failed, so, I am trying see the size my List for know if I insert success...
I get this error:
java.lang.Exception: Method test should have no parameters
at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:76)
at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
at org.junit.runners.BlockJUnit4ClassRunner.validateTestMethods(BlockJUnit4ClassRunner.java:208)
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:188)
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.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
I am new in Junit, mongodb ... I only want use mongoDB embebed and insert and check my bbdd .... thanks...
You forgot an annotation on the class level: #ExtendWith(SpringExtension.class)
#DataMongoTest
#ExtendWith(SpringExtension.class)
public class TestApplicationConfiguration {
#Test
public void test(#Autowired MongoTemplate mongoTemplate) {
// your test code
}
}
Please read the tutorial carefully.
Here is the link to the GitHub Repo where you can find the pom.xml and all the source code as well:
https://github.com/eugenp/tutorials/tree/master/persistence-modules/spring-boot-persistence-mongodb
Related
I am new to Flink CEP and trying to test basic things -
In below code my expectation is all the input should matched in patter and should print as matched result.
But somehow nothing is matching ('matechedStream.print()') any idea about the reason ?
Any suggestion/help would be much appreciated.
package com.o9.flink;
import com.o9.flink.asyncio.DemandSupply;
import org.apache.flink.cep.CEP;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.functions.PatternProcessFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
public class DemandSupplyPattern {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStream<String> keyedInputStream = env.fromElements("AAA","BBB","CCC");
Pattern<String, ?> dspattern = Pattern.<String>begin("start");
PatternStream<String> patternStream = CEP.pattern(keyedInputStream, dspattern);
DataStream<String> matechedStream = patternStream.process(new PatternProcessFunction<String, String>() {
#Override
public void processMatch(Map<String, List<String>> map, Context context, Collector<String> collector) throws Exception {
collector.collect(map.get("start").toString());
}
});
matechedStream.print();
env.execute("DemandSupply-CEP");
}
}
Maven dependencies :
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-runtime</artifactId>
<version>${flink.version}</version>
<!--<scope>test</scope>-->
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
<version>${flink.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-java</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-avro</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java</artifactId>
<version>${flink.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-clients</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-statebackend-rocksdb</artifactId>
<version>${flink.version}</version>
<!--<scope>test</scope>-->
</dependency>
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-cep</artifactId>
<version>${flink.version}</version>
<!--<scope>provided</scope>-->
</dependency>
</dependencies>
Thanks
Mahendra
FlinkCEP by default uses EventTime which relies on a WaterMark to help those events proceeding. It may helps if you switch it to ProcessingTime.
PatternStream<String> patternStream = CEP.pattern(keyedInputStream, dspattern).inProcessingTime();
If you have no idea about the difference and hence the time semantics, you can check official doc at
Flink Notion of Time
I'm working on a basic application using Java Spring Boot, I'm stuck on this error:
This is the error message:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-12-16 12:44:40.321 ERROR 5698 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.htamayo.sbcrashcourse.SbcrashcourseApplication required a bean named 'entityManagerFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
My main class looks like this:
package com.htamayo.sbcrashcourse;
import com.htamayo.sbcrashcourse.lendingengine.domain.model.User;
import com.htamayo.sbcrashcourse.lendingengine.domain.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#ComponentScan(basePackages = {"com.htamayo.sbcrashcourse.lendingengine"})
#EnableJpaRepositories("com.htamayo.sbcrashcourse.lendingengine.domain.repository")
public class SbcrashcourseApplication implements CommandLineRunner {
#Autowired
private UserRepository userRepository;
public static void main(String[] args) {SpringApplication.run(SbcrashcourseApplication.class, args);}
#Override
public void run(String... args) throws Exception {
userRepository.save(new User(1, "John", "B", 27, "Software Developer"));
userRepository.save(new User(2, "Peter", "C", 21, "Pilot"));
userRepository.save(new User(3, "Henry", "E", 21, "Unemployed"));
}
}
UserRepository class is this:
package com.htamayo.sbcrashcourse.lendingengine.domain.repository;
import com.htamayo.sbcrashcourse.lendingengine.domain.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
And my pom.xml looks like this:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.32.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.5.7.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
org.springframework.boot
spring-boot-maven-plugin
I've been searching for solutions on Google but so far nothing, so my question is: I don't understand how to overcome the EntityManagerFactory error, am I missing a dependency? or should I refactor my code? any solutions?
Thanks a lot for your suggestions.
Well, after 17 days finally I got the solution:
my problem was on properties file, for some reason I used this line (I can't remember why):
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
I just commented it and problem solved.
Lessons learned:
always document your code
JitterTed's discord is a great source of answers.
I'm trying to create a project that uses Hibernate Panache and Rest, similar to the quickstart on https://github.com/quarkusio/quarkus-quickstarts/tree/master/hibernate-orm-panache-resteasy.
When I try to #Post an entity that extends PanacheEntity, as shown below, I get the following error:
javax.ws.rs.ProcessingException: RESTEASY008200: JSON Binding deserialization error: Can't create instance
Entity
#Entity
#Cacheable
class Trade extends PanacheEntity {
#Column(length = 40, unique = true)
String name;
}
Rest resource
import javax.enterprise.context.ApplicationScoped;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Path("/trades")
#ApplicationScoped
#Produces("application/json")
#Consumes("application/json")
public class TradeReporterResource {
#POST
#Transactional
public Response add(Trade trade) {
System.out.println("begin");
//t.closePrice = trade.closePrice;
System.out.println("persisting");
trade.persist();
System.out.println("persisted");
return Response.ok(trade).build();
}
}
Pom dependencies
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-bom</artifactId>
<version>${quarkus.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
</dependencies>
Problem appears to be with Penache
When I remove the extends PanacheEntity from the Trade entity, then at least I can POST successfully.
The problem turns out to be rather simple, all you need to do is make class Trade a public class.
It should be noted that this is not a Quarkus limitation, but a JSON-B limitation (which requires de-serialized classes to have a public or protected no-arg constructor - see section 3.7 of the JSON-B spec)
Using the information provided below can you answer the following questions:
What container provider supports org.apache.cxf.jaxrs.JAXRSServerFactoryBean so that I may add my application using org.glassfish.jersey.server.ContainerFactory when creating an end point?
What is wrong with the below application that causes (JAXRSServerFactoryBean)RuntimeDelegate.getInstance().createEndpoint(app, JAXRSServerFactoryBean.class); to throw an illegal argument exception?
I am attempting to deploy a JAX-RS application that uses annotations (no web.xml) to system that uses a Java Application Manager (it is a proprietary system that has ported over some application manager libraries but I am not sure what those are due to little supporting documentation around it).
At a high level I have a Java application that uses JAX-RS annotations, such as ApplicationPath, Path, Produces/Consumes, and JsonProperty, to attempt to create an endpoint on a "application server". I say "application server" because I have no documentation around this system so I am just going to call it that. When attempting to start the application I get the following exception:
java.lang.IllegalArgumentException: No container provider supports the type class org.apache.cxf.jaxrs.JAXRSServerFactoryBean
at org.glassfish.jersey.server.ContainerFactory.createContainer(ContainerFactory.java:64)
at org.glassfish.jersey.server.internal.RuntimeDelegateImpl.createEndpoint(RuntimeDelegateImpl.java:47)
at com.app.Server.startServer(Server.java:182)
I have researched the java.lang.IllegalArgumentException thrown by the org.glassfish.jersey.server.internal.RuntimeDelegateImpl.createEndpoint function. I am not sure why it would do this because on the cover it appears like the application class is annotated correctly and extends Application.
I was able to look at the Server's class code and here is what is being done:
Server Code
Here a snippet portion of com.app.Server.startServer(Server.java:182) code, I cannot alter this code:
inside of startServer...
Application app = (Application) Class.forName("com.app.MyApplication").newInstance();
JAXRSServerFactoryBean jaxrsServerFactory = (JAXRSServerFactoryBean)RuntimeDelegate.getInstance().createEndpoint(app, JAXRSServerFactoryBean.class);
Now my code:
Application Code
MyApplication
package com.app;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import com.app.services.ServiceOne;
#ApplicationPath("base/path")
public class MyApplication extends Application {
public MyApplication() {
System.out.println(Long.toString(System.nanoTime()) + " " + this.getClass().getName() + " constructor called...");
}
/* (non-Javadoc)
* #see javax.ws.rs.core.Application#getClasses()
*/
#Override
public Set<Class<?>> getClasses() {
System.out.println(Long.toString(System.nanoTime()) + " " + this.getClass().getName() + " getClasses() method called...");
Set<Class<?>> classes = new HashSet<>();
classes.add(ServiceOne.class);
return classes;
}
}
My Application's Services
package com.app.services.ServiceOne;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
// pretend the model imports are here...
#Path("serviceOne")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class ServiceOne {
#PUT
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public ResponseObject performService(InputObject body) throws NotFoundException {
// do whatever to get result and send...
}
}
Pom.xml Plugins and Dependencies
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jdk-http</artifactId>
<version>2.28-RC4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.28-RC4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.28-RC4</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.28-RC4</version>
</dependency>
</dependencies>
Thanks again for your help!
I figured out the answer to my question.
The system I was attempting to deploy my application to already had jar files installed on the system in various directories.
I updated my application to include those jar files. This was done by updating a descriptor that I use to deploy the application to the system.
Then I and set the scope of certain dependencies in my pom.xml to <scope>provided</scope> so that when the application was packaged by maven, those dependencies would not be included in the final jar.
Below is an example:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-jdk-http</artifactId>
<version>2.28-RC4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.28-RC4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.28-RC4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.28-RC4</version>
<scope>provided</scope>
</dependency>
</dependencies>
This was fixed in my side by excluding jersey-server which has its own META-INF/services/javax.ws.rs.ext.RuntimeDelegate (see RuntimeDelegate.JAXRS_RUNTIME_DELEGATE_PROPERTY), hence preventing the proper loading of org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl. In my case, jersey-server was brought transitively by hadoop-mapreduce-client-core:
<dependency>
<groupId>XXX</groupId>
<artifactId>YYY</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
</exclusion>
</exclusions>
</dependency>
I'm trying to follow the examples in Spring in Action (4th edition), chapter 5 to create my own project. (Still a newbie at enterprise-level stuff) I'm using a Windows 7 PC, Java 7, Spring 4 and Maven. When I run my ClinicalNoteControllerTest, the test fails with a NoSuchMethod error on a specific line. But I've researched this line, and it seems to be written correctly. It definitely follows the example in the book. I've debugged, but can't find anything in what turns up there. I'm wondering if I don't have the correct configuration in my pom.xml file?
You guys are always so helpful, and I'll appreciate any help you can give finding a solution here. But I also want to become a better troubleshooter myself and not just run to stackoverflow every time I hit a bump. So any tips you can give on how I could troubleshoot this problem myself will be greatly appreciated.
Here is the test:
package com.kwalker.practicewellness;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import static org.mockito.Mockito.*;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.hamcrest.Matchers.*;
import org.springframework.web.servlet.view.InternalResourceView;
import com.kwalker.practicewellness.data.ClinicalNoteRepository;
import com.kwalker.practicewellness.domain.ClinicalNote;
import com.kwalker.practicewellness.web.ClinicalNoteController;
public class ClinicalNoteControllerTest {
#Test
public void shouldShowRecentClinicalNotes() throws Exception {
List<ClinicalNote> expectedClinicalNotes = createClinicalNoteList(20);
ClinicalNoteRepository mockNoteRepository = mock(ClinicalNoteRepository.class);
when(mockNoteRepository.findClinicalNotes(Long.MAX_VALUE, 20)).thenReturn(expectedClinicalNotes);
ClinicalNoteController noteController = new ClinicalNoteController(mockNoteRepository);
MockMvc mockMvc = standaloneSetup(noteController).setSingleView(
new InternalResourceView("/WEB-INF/views/clinicalNotes.jsp")).build();
mockMvc.perform(get("/clinical-notes"))
.andExpect(view().name("clinicalNotes"))
.andExpect(model().attributeExists("clinicalNoteList"))
.andExpect(model().attribute("clinicalNoteList", hasItems(expectedClinicalNotes.toArray())));
}
private List<ClinicalNote> createClinicalNoteList(int count) {
List<ClinicalNote> clinicalNotes = new ArrayList<ClinicalNote>();
for (int i=0; i < count; i++) {
clinicalNotes.add(new ClinicalNote("Note " + i, new Date()));
}
return clinicalNotes;
}
}
Here is the ClinicalNoteController:
package com.kwalker.practicewellness.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.kwalker.practicewellness.data.ClinicalNoteRepository;
#Controller
#RequestMapping("/clinical-notes")
public class ClinicalNoteController {
private ClinicalNoteRepository noteRepository;
#Autowired
public ClinicalNoteController(ClinicalNoteRepository noteRepository) {
this.noteRepository = noteRepository;
}
#RequestMapping(method=RequestMethod.GET)
public String clinicalNotes(Model model) {
model.addAttribute("clinicalNoteList", noteRepository.findClinicalNotes(Long.MAX_VALUE, 20));
return "clinicalNotes";
}
}
Here is what prints out on the console when I run the test:
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/clinical-notes],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.kwalker.practicewellness.web.ClinicalNoteController.clinicalNotes(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext#41494678
INFO : org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 16 ms
Here is the failure trace:
java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V
at org.hamcrest.core.IsCollectionContaining.matchesSafely(IsCollectionContaining.java:31)
at org.hamcrest.core.IsCollectionContaining.matchesSafely(IsCollectionContaining.java:14)
at org.hamcrest.TypeSafeDiagnosingMatcher.matches(TypeSafeDiagnosingMatcher.java:55)
at org.hamcrest.core.AllOf.matches(AllOf.java:24)
at org.springframework.test.util.MatcherAssertionErrors.assertThat(MatcherAssertionErrors.java:65)
at org.springframework.test.web.servlet.result.ModelResultMatchers$1.match(ModelResultMatchers.java:56)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
at com.kwalker.practicewellness.ClinicalNoteControllerTest.shouldShowRecentClinicalNotes(ClinicalNoteControllerTest.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Here is my POM file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kwalker</groupId>
<artifactId>practicewellness</artifactId>
<name>Practice Wellness</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.1.4.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
</dependency>
<!-- Misc -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
Here is my webapp initializer:
package com.kwalker.practicewellness.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WellnessWebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Here is my WebConfig file:
package com.kwalker.practicewellness.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.kwalker.practicewellness.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Here is the RootConfig class:
package com.kwalker.practicewellness.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"com.kwalker.practicewellness"},
excludeFilters={#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
public class RootConfig {
}
This exact problem is addressed on Ted Vinke's blog from December 2013: Mixing JUnit, Hamcrest and Mockito
I used the code given on this page to modify my POM file (which basically involved rearranging mockito, junit and hamcrest, and excluding hamcrest on the mockito dependency). IMPORTANT TO NOTE: I was using the latest versions of these resources, and the fix DID NOT WORK until I made the versions in my POM file match the versions shown on the page at that link. Here is the text from the link:
This could be due to the fact that JUnit itself brings along its own version of Hamcrest as a transitive dependency. Now if you would be using JUnit 4.11 it would depending on Hamcrest 1.3 already.... Getting above error would be weird – since the describeMismatch method is present in org.hamcrest.Matcher interface. There seems to be an older version of org.hamcrest.Matcher present on the classpath to which org.junit.Assert.assertThat delegates. If you run this from Eclipse or IntelliJ, there’s a high chance that the IDE uses its own version of JUnit instead of your Maven dependency....
The article continues:
If we we’re looking in Eclipse for the Matcher classes we e.g. could see that there’s also one in mockito-all-1.9.5.jar.... Seems mockito-all is incompatible with JUnit 4.11 for backwards-compatibility reasons. The Hamcrest version 1.1 Matcher has been packaged within the dependency, so we can not exclude it.... Luckily for us, Mockito allows to us to use a mockito-core dependency instead of mockito-all. Running a dependency check (with dependency:tree or online) shows us it depends on hamcrest-core..... We can exclude it in the pom.xml and – no more NoSuchMethodError. Here’s the final combination of dependencies in our case:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
I just had a similar issue and I was trying to track where junit, mockito and hamcrest was been import as dependency to understand what have changed (we have not changed the code in any way).
We found a "RELEASE" value as version to a pom dependency (spring-test from org.springframework). So looks like a new version of this dependency is no compatible with the others libs. After removing the version tag the problem was solved. After that we even removed the depedency since it was already contained on other dependencies.