I am setting up the unit testing on my #RestController's, but It is not working correctly.
This is only a unit test to validate the answer from the method of the RestEndpoint, but It is not working, please help me because I tried a lot of configurations and read the documentation and nothing worked.
This is my endpoint:
#RestController
#RequestMapping("/clients")
public class ClientsEndpoint extends RestConfiguration {
#Autowired
private IClientService clientService;
#GetMapping(value = "/{id}")
private Object getById(#PathVariable(required = true) Long id) {
try {
Optional<Client> clientOptional = clientService.getById(id);
if (clientOptional.isPresent()) {
return clientOptional.get();
} else
return new GeneralResponse(ErrorsEnum.CLIENT_NOT_FOUND);
} catch (Exception e) {
log.log(Level.SEVERE, "Problemas al obtener datos del cliente con id: " + id, e);
return new GeneralResponse(ErrorsEnum.GENERAL_ERROR);
}
}
This is my Unit Test where I only added the mock of the endpoint and a simple call is done:
#RunWith(SpringRunner.class)
#WebMvcTest(ClientsEndpoint.class)
#ContextConfiguration(classes={ApplicationConfiguration.class})
public class QuarzoApiApplicationTests {
#Autowired
private MockMvc mockMvc;
#MockBean
private IClientService clientService;
#Test
public void getById() throws Exception {
Client client = new Client("Test", "Test", "Test", (byte) 1,
"Test", "Test", "Test", "Test", (byte) 1,
(byte) 1, (short)1, "Test" );
Optional<Client> clientOptional = Optional.of(client);
BDDMockito.given(clientService.getById(anyLong())).willReturn(clientOptional);
this.mockMvc.perform(get("/clients/1")
.header("Authorization","Bearer " + TestUtils.createToken("miltonc")))
.andExpect(status().isOk());
}
Results I am getting after running the unit test:
2019-08-27 10:01:18.505 INFO 23606 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#7da39774, org.springframework.security.web.context.SecurityContextPersistenceFilter#5b7c8930, org.springframework.security.web.header.HeaderWriterFilter#4277127c, org.springframework.web.filter.CorsFilter#441b8382, org.springframework.security.web.authentication.logout.LogoutFilter#1a6dc589, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#40e32762, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#6f231ced, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#1df1ced0, org.springframework.security.web.session.SessionManagementFilter#2c05ff9d, org.springframework.security.web.access.ExceptionTranslationFilter#2a8a4e0c, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#27755487]
2019-08-27 10:01:18.526 INFO 23606 --- [ main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2019-08-27 10:01:18.527 INFO 23606 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2019-08-27 10:01:18.533 INFO 23606 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 6 ms
2019-08-27 10:01:18.555 INFO 23606 --- [ main] i.q.quarzoapi.QuarzoApiApplicationTests : Started QuarzoApiApplicationTests in 1.371 seconds (JVM running for 1.825)
MOCK org.springframework.test.web.servlet.MockMvc#770beef5
MockHttpServletRequest:
HTTP Method = GET
Request URI = /clients/1
Parameters = {}
Headers = [Authorization:"Bearer eyJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1NjY5MTQ0NzgsImlzcyI6IlFVQVJaTyIsInN1YiI6Im1pbHRvbmMiLCJleHAiOjE1NjY5NjQ4MDB9.hLu1Mcl_K-8smYnZnDu1ubkVTuNCkQnqhIQuypBsKBzQYxMlYlxqXhsYLCMB5iViCcDK33WXvO1Pjp15TR1ICg"]
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at io.quarzo.quarzoapi.QuarzoApiApplicationTests.getById(QuarzoApiApplicationTests.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
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)
2019-08-27 10:01:18.772 INFO 23606 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
I finally solved this. I needed to include the #ComponentScan(basePackages = "io.quarzo.api.endpoints") to refer the endpoints I am trying to test.
My Test configuration:
#Configuration
#ComponentScan(basePackages = "io.quarzo.api.endpoints")
public class ApplicationConfiguration extends WebSecurityConfigurerAdapter {
After that, I had to Mock every bean I was using in the endpoints.
#MockBean(name = "clientRegistrationSingleton")
private Map<String, Client> clientsRegistering;
#MockBean
private IClientService clientService;
#MockBean
private IClientRepository clientRepository;
After that all was working ok, I can run the test and mock every Bean to test my #RestController's.
Related
I am new to spring boot, i am getting this error since a while, unfortunately can't fix it. I am googling since then but still not find what i did wrong. Find below my code:
Entity
#Entity
#Table(name="compagnie")
public class Compagnie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_compagnie")
private int idCompagnie;
#Column(name="nom_compagnie")
private String nomCompagnie;
#Column(name="nom_court_compagnie")
private String nomCourtCompagnie;
#Column(name="logo_compagnie")
private String logoCompagnie;
public int getIdCompagnie() {
return idCompagnie;
}
public void setIdCompagnie(int idCompagnie) {
this.idCompagnie = idCompagnie;
}
public String getNomCompagnie() {
return nomCompagnie;
}
public void setNomCompagnie(String nomCompagnie) {
this.nomCompagnie = nomCompagnie;
}
public String getNomCourtCompagnie() {
return nomCourtCompagnie;
}
public void setNomCourtCompagnie(String nomCourtCompagnie) {
this.nomCourtCompagnie = nomCourtCompagnie;
}
public String getLogoCompagnie() {
return logoCompagnie;
}
public void setLogoCompagnie(String logoCompagnie) {
this.logoCompagnie = logoCompagnie;
}
}
Dao
#Component
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {
#Query("select c from Compagnie c where idCompagnie != :idCompagnie")
List<Compagnie> getAllCompagnieNonAssurAstuce(#Param("idCompagnie") int idCompagnie);
#Query("select c from Compagnie c where nomCompagnie = :nomCompagnie")
Compagnie getCompagnieByNom(#Param("nomCompagnie") String nomCompagnie);
}
Main
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
private CompagnieDao compagnieDao;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("tic toc");
List<Compagnie> compagnies = compagnieDao.findAll();
compagnies.forEach(compagnie -> System.out.println(compagnie.getNomCompagnie()));
}
}
Error
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-30 11:54:42.817 ERROR 10136 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field compagnieDao in com.assurastuce.Application required a bean of type 'com.dao.CompagnieDao' 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 of type 'com.dao.CompagnieDao' in your configuration.
Thank you for your help
I changed the spring version from 2.4.1 to 2.3.4.RELEASE and now getting this error
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.assurastuce.Application.main(Application.java:20) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_271]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_271]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: java.lang.NullPointerException: null
at com.assurastuce.Application.run(Application.java:26) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
... 10 common frames omitted
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#19b4bd36{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] org.eclipse.jetty.server.session : node0 Stopped scavenging
2020-12-31 08:26:45.405 INFO 11520 --- [ restartedMain] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2020-12-31 08:26:45.407 INFO 11520 --- [ restartedMain] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#4bfa6d74{application,/,[file:///C:/Users/LAKATAN%20Adebayo%20G.%20W/AppData/Local/Temp/jetty-docbase.8010039629830210588.8080/],UNAVAILABLE}
2020-12-31 08:26:45.430 INFO 11520 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-31 08:26:45.434 INFO 11520 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-31 08:26:45.438 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-31 08:26:45.465 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Probably the folder structure is not correct.
Could you please add this line of code and check if this works for you.
#SpringBootApplication
#ComponentScan(value = "com.dao.CompagnieDao")
public class Application implements CommandLineRunner {
Also, I think it would be more correct if you replace the #Component with the #Repository annotation.
#Repository
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {
I am trying to create a simple Resttemplate which will fetch the schema from Schema Registary and if response is 200 it will fetch the Schema ID and send it along with message in Avro format to kafka. Here is my code:
.
#SpringBootApplication
public class DemoApplication implements CommandLineRunner{
String kafkarwsrproxyURL = String.format("%s/topics/%s", "https://kafka-rest-proxy-**********", "test-topic");
String schemaurl = String.format("%s/subjects/%s/versions/latest", "https://schema-registry-*********", "test-topic");
#Autowired
private RestTemplate restTemplate;
#Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
ObjectMapper obj = new ObjectMapper();
JSONObject event = new JSONObject();
JSONObject record = new JSONObject();
JSONObject eventenvolpe = new JSONObject();
JSONObject jsondata = new JSONObject();
JSONArray jsonarray =new JSONArray();
JSONObject recordvalue =new JSONObject();
// connecting to schema registary and getting back schema
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("application/vnd.schemaregistry.v1+json"));
headers.setBasicAuth("username", "password");
HttpEntity<String> SchemaEntity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(schemaurl, HttpMethod.GET, SchemaEntity, String.class);
if(result.getStatusCodeValue()==200) {
JsonNode rootNode = obj.readTree(result.getBody());
JsonNode schema_id = rootNode.path("id");//fetchinf schema id form schema
event = new JSONObject();
record = new JSONObject();
eventenvolpe = new JSONObject();
jsondata = new JSONObject();
jsondata.put("data", obj.writeValueAsString(new Data("test1",1)));
eventenvolpe.put("event_envelope", jsondata);
recordvalue.put("value", eventenvolpe);
jsonarray.put(recordvalue);
event.put("value_schema_id", schema_id);
event.put("records", recordvalue);//setting up event object to send to kafka
System.out.println(event);
//Sending message to kafka
HttpHeaders messageheaders = new HttpHeaders();
messageheaders.setContentType(MediaType.valueOf("application/vnd.kafka.avro.v2+json"));
messageheaders.setBasicAuth("username", "password");
HttpEntity<JSONObject> message = new HttpEntity<JSONObject>(event,messageheaders );
ResponseEntity<String> result1 = restTemplate.exchange(kafkarwsrproxyURL, HttpMethod.POST, message, String.class);
if(result1.getStatusCodeValue()==200) {
System.out.println("Message is pushed to Kafka");
}
}
}
}
I am successfully able to fetch schema form registry but while sending back to kafka getting error.
2020-06-30 20:02:56.078 INFO 7972 --- [ main] com.example.demo.DemoApplication :
No active profile set, falling back to default profiles: default
2020-06-30 20:02:59.235 INFO 7972 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer :
Tomcat initialized with port(s): 8089 (http)
2020-06-30 20:02:59.263 INFO 7972 --- [ main] o.apache.catalina.core.StandardService :
Starting service [Tomcat]
2020-06-30 20:02:59.264 INFO 7972 --- [ main] org.apache.catalina.core.StandardEngine :
Starting Servlet engine: [Apache Tomcat/9.0.36]
2020-06-30 20:02:59.434 INFO 7972 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] :
Initializing Spring embedded WebApplicationContext
2020-06-30 20:02:59.434 INFO 7972 --- [ main] w.s.c.ServletWebServerApplicationContext :
Root WebApplicationContext: initialization completed in 3269 ms
2020-06-30 20:02:59.847 INFO 7972 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor :
Initializing ExecutorService 'applicationTaskExecutor'
2020-06-30 20:03:00.238 INFO 7972 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer :
Tomcat started on port(s): 8089 (http) with context path ''
2020-06-30 20:03:00.251 INFO 7972 --- [ main] com.example.demo.DemoApplication :
Started DemoApplication in 4.945 seconds (JVM running for 5.758)
{"records":{"value":{"event_envelope":{"data":"
{\"test\":\"test1\",\"testEventId\":1}"}}},"value_schema_id":"5"}
2020-06-30 20:03:02.276 INFO 7972 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with
'debug' enabled.
2020-06-30 20:03:02.282 ERROR 7972 --- [ main] o.s.boot.SpringApplication :
Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-
2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-
2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-
2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-
2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-
2.3.1.RELEASE.jar:2.3.1.RELEASE]
at com.example.demo.DemoApplication.main(DemoApplication.java:44) [classes/:na]
Caused by: org.springframework.web.client.RestClientException: No HttpMessageConverter for
org.json.JSONObject and content type "application/vnd.kafka.avro.v2+json"
at `org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:961) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:737) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE] at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:583) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE] at com.example.demo.DemoApplication.run(DemoApplication.java:91) [classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE] ... 5 common frames omitted
2020-06-30 20:03:02.878 INFO 7972 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down
ExecutorService 'applicationTaskExecutor'`
It seems that the trouble is cause by the fact that your client doesn't know how to read this "exotic" data type: "application/vnd.kafka.avro.v2+json"
Here's a possible solution in this post:
no suitable HttpMessageConverter found for response type
To sum up - you either have to register the corresponding HttpMessageConverter for the MIME type "application/vnd.kafka.avro.v2+json" or change (if you have access) the returning MIME type from server. You can also "hack" a quick proxy script, so that it goes to server and fetches data and then sends it to you client with changed MIME type.
Dependencies:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
And the code snippet:
#Bean
public RestTemplate restTemplate() {
final RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
List<MediaType> types = Arrays.asList(
new MediaType("application", "*+json", DEFAULT_CHARSET)
);
converter.setSupportedMediaTypes(types);
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
}
I'm stuck on setting up a feignclient of one of my microservices.
I use criteria (for filtering) and pagination.
On one of my microservices I have a service rest and the other use a feignclient to request it.
AccountCriteria (criteria interface from jhipster)
public class AccountCriteria implements Serializable, Criteria {
private LongFilter id;
private StringFilter user;
private LongFilter bankWebId;
private LongFilter bankApiId;
private LongFilter deactivationReasonId;
public AccountCriteria() {
}
public AccountCriteria(AccountCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.user = other.user == null ? null : other.user.copy();
this.bankWebId = other.bankWebId == null ? null : other.bankWebId.copy();
this.bankApiId = other.bankApiId == null ? null : other.bankApiId.copy();
this.deactivationReasonId = other.deactivationReasonId == null ? null : other.deactivationReasonId.copy();
}
#Override
public Criteria copy() {
return new AccountCriteria(this);
}
}
AccountIdentifierResource (Rest resource)
#RestController
#RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AccountIdentifierResource {
log.debug("REST request to get AccountIdentifiers by criteria: {}", criteria);
Page<AccountIdentifier> page = accountIdentifierQueryService.findByCriteria(criteria, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
IdentityProviderFeignClient (feign client)
#AuthorizedFeignClient(name = "identityprovider")
public interface IdentityProviderFeignClient {
#GetMapping("/api/account-identifiers")
List<AccountIdentifier> getAllAccountIdentifiers(AccountCriteria criteria,
Pageable pageable, #RequestParam("queryParams") MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder);
}
IdentityProviderService (the service interface)
public interface IdentityProviderService {
List<AccountIdentifier> getAllAccountIdentifiers(AccountCriteria criteria, Pageable pageable, MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder);
}
IdentityProviderServiceImpl (the service implementation)
#Service
public class IdentityProviderServiceImpl implements IdentityProviderService {
private final Logger log =
LoggerFactory.getLogger(IdentityProviderServiceImpl.class);
private final IdentityProviderFeignClient identityProviderFeignClient;
public IdentityProviderServiceImpl(IdentityProviderFeignClient identityProviderFeignClient) {
this.identityProviderFeignClient = identityProviderFeignClient;
}
#Override
public List<AccountIdentifier> getAllAccountIdentifiers(AccountCriteria criteria, Pageable pageable, MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder) {
log.debug("Request to get all AccountIdentifier from IdentityProvider with criteria : {}", criteria);
return this.identityProviderFeignClient.getAllAccountIdentifiers(criteria, pageable, queryParams, uriBuilder);
}
}
FeignConfiguration
#Configuration
#EnableFeignClients(basePackages = "com.soft.jobstrategy")
#Import(FeignClientsConfiguration.class)
public class FeignConfiguration {
/**
* Set the Feign specific log level to log client REST requests.
*/
#Bean
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
}
For now it's impossible to run the application.
I get the following traceback:
[INFO] Running com.soft.jobstrategy.config.timezone.HibernateTimeZoneIT
:: JHipster ? :: Running Spring Boot 2.1.6.RELEASE ::
:: https://www.jhipster.tech ::
2019-10-04 16:07:44.465 WARN 2736 --- [ main] kafka.server.BrokerMetadataCheckpoint : No meta.properties file under dir C:\Users\maktouf\AppData\Local\Temp\kafka-6358187594718130765\meta.properties
2019-10-04 16:07:45.097 WARN 2736 --- [ main] kafka.server.BrokerMetadataCheckpoint : No meta.properties file under dir C:\Users\maktouf\AppData\Local\Temp\kafka-6358187594718130765\meta.properties
2019-10-04 16:07:45.343 INFO 2736 --- [ main] c.b.j.c.timezone.HibernateTimeZoneIT : No active profile set, falling back to default profiles: default
2019-10-04 16:07:49.628 WARN 2736 --- [ main] c.b.j.config.CacheConfiguration : No discovery service is set up, Hazelcast cannot create a cluster.
2019-10-04 16:07:51.266 WARN 2736 --- [ main] com.hazelcast.instance.Node : [192.168.1.21]:5701 [dev] [3.11.4] No join method is enabled! Starting standalone.
2019-10-04 16:07:57.509 WARN 2736 --- [ main] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2019-10-04 16:07:57.918 WARN 2736 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creatin
g bean with name 'identityProviderServiceImpl' defined in file [C:\developpement\javaenv\workspace\job_strategy\target\classes\com\soft\jobstrategy\service\impl\IdentityProviderServiceImpl.class]: Unsatisfied dependency expressed through constructor par
ameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.soft.jobstrategy.client.IdentityProviderFeignClient': FactoryBean threw exception on object creation; nested exception is java.lang
.IllegalStateException: Method has too many Body parameters: public abstract java.util.List com.soft.jobstrategy.client.IdentityProviderFeignClient.getAllAccountIdentifiers(com.soft.jobstrategy.service.dto.AccountCriteria,org.springframework.dat
a.domain.Pageable,org.springframework.util.MultiValueMap,org.springframework.web.util.UriComponentsBuilder)
2019-10-04 16:07:57.965 INFO 2736 --- [ main] c.b.j.config.CacheConfiguration : Closing Cache Manager
2019-10-04 16:08:01.744 ERROR 2736 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'identityProviderServiceImpl' defined in file [C:\developpement\javaenv\workspace\job_strategy\target\classes\com\soft\jobstrategy\service\impl\IdentityProvi
derServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.soft.jobstrategy.client.IdentityProviderFeignClient'
: FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Method has too many Body parameters: public abstract java.util.List com.soft.jobstrategy.client.IdentityProviderFeignClient.getAllAccountIdentifiers(c
om.soft.jobstrategy.service.dto.AccountCriteria,org.springframework.data.domain.Pageable,org.springframework.util.MultiValueMap,org.springframework.web.util.UriComponentsBuilder)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:119)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:97)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$5(ClassTestDescriptor.java:349)
at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.executeAndMaskThrowable(JupiterTestDescriptor.java:215)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassTestDescriptor.java:349)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:743)
at java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:742)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstancePostProcessors(ClassTestDescriptor.java:348)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:270)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$2(ClassTestDescriptor.java:259)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$3(ClassTestDescriptor.java:263)
at java.util.Optional.orElseGet(Optional.java:267)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstanceProvider$4(ClassTestDescriptor.java:262)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:82)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:59)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$0(NodeTestTask.java:83)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:83)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:69)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$4(NodeTestTask.java:112)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:72)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:98)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:74)
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:220)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:150)
at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:124)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.soft.jobstrategy.client.IdentityProviderFeignClient': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateExcept
ion: Method has too many Body parameters: public abstract java.util.List com.soft.jobstrategy.client.IdentityProviderFeignClient.getAllAccountIdentifiers(com.soft.jobstrategy.service.dto.AccountCriteria,org.springframework.data.domain.Pageable,o
rg.springframework.util.MultiValueMap,org.springframework.web.util.UriComponentsBuilder)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:178)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1674)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1249)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:257)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1474)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1431)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1214)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
... 73 common frames omitted
Thanks everyone for your help.
Edit :
Finally the answer of Murilo Prado resolved the issue.
I also edited the code of the feign client :
IdentityProviderFeignClient (feign client)
#AuthorizedFeignClient(name = "identityprovider")
public interface IdentityProviderFeignClient {
#GetMapping("/api/account-identifiers")
List<AccountIdentifier> getAllAccountIdentifiers(#QueryParam("search") String criteria,
Pageable pageable, #RequestParam("queryParams") MultiValueMap<String, String> queryParams);
}
Try this
public class FeignConfig {
#Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
#Bean
#ConditionalOnMissingBean
public Decoder feignDecoder() {
return new OptionalDecoder(new ResponseEntityDecoder(new SpringDecoder(this.messageConverters)));
}
#Bean
#ConditionalOnMissingBean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
I am fairly new to unit testing and trying to test a simple function that returns a query. In my unit test, I am getting the NullPointerException after calling the method. I assume mongoOperations is null, and guessing that is the reason why it is returning NPE. I am using fongo to mock the mongoDB and I configured the spring context in testConfigurationContext.xml file.
This is the class I want to test:
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion
findByDBAndCollection(String dbName, String collectionName) {
//below is the line 27 on error console
return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
}
}
This is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
private DataVersionDaoMongo dataVersionDaoMongo = new DataVersionDaoMongo();
private MongoOperations mongoOperations;
private DataVersion dataVersion;
#Rule
public FongoRule fongoRule = new FongoRule();
#Test
public void findByDBAndCollection() {
String dbname = "mydb";
String collectionName = "mycollection";
DB db = fongoRule.getDB(dbname);
DBCollection collection = db.getCollection(collectionName);
Mongo mongo = fongoRule.getMongo();
collection.insert(new BasicDBObject("name", "randomName"));
//below is the line 63 on error console
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}
This is the applicationContext file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<bean name="fongo" class="com.github.fakemongo.Fongo">
<constructor-arg value="InMemoryMongo" />
</bean>
<bean id="mongo" factory-bean="fongo" factory-method="getMongo" />
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />
<!-- localhost settings for mongo -->
<!--<mongo:db-factory id="mongoDbFactory" />-->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory"/>
</bean>
</beans>
This is the error on console:
java.lang.NullPointerException
at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongo.findByDBAndCollection(DataVersionDaoMongo.java:27)
at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongoTest.findByDBAndCollection(DataVersionDaoMongoTest.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
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)
I am guessing I am missing something. Any help would be greatly appreciated!
I have never used Fongo, but usually I mock the mongo server with flapdoodle. This is easy to implements.
I would like to recommend it.
https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.1.1</version>
<scope>test</scope>
</dependency>
You are not auto-wiring DataVersionDaoMongo in you unit test, also mongoOperations bean either need to be auto-wired or injected via constructor.
In you Repo class
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
#Autowire MongoOperations mongoOperations;
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion findByDBAndCollection(String dbName, String collectionName) {
//below is the line 27 on error console
return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
}
}
and in your unit test, you no need to use new for bean creation.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
#Autowire
private DataVersionDaoMongo dataVersionDaoMongo;
#Autowire
private MongoOperations mongoOperations; // you can remove this, if not using it
private DataVersion dataVersion;
#Rule
public FongoRule fongoRule = new FongoRule();
#Test
public void findByDBAndCollection() {
String dbname = "mydb";
String collectionName = "mycollection";
DB db = fongoRule.getDB(dbname);
DBCollection collection = db.getCollection(collectionName);
Mongo mongo = fongoRule.getMongo();
collection.insert(new BasicDBObject("name", "randomName"));
//below is the line 63 on error console
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}
I have following code:
#Test
public void testSaveValid() throws Exception {
MockRoundtrip trip = new MockRoundtrip(mockServletContext,
ContactFormActionBean.class, mockSession);
trip.setParameter("contact.email", "test#test.com");
trip.setParameter("contact.phoneNumber", "654-456-4567");
trip.execute("save");
ContactFormActionBean bean =
trip.getActionBean(ContactFormActionBean.class);
assertEquals(0,
bean.getContext().getValidationErrors().size());
PhoneNumber pn = bean.getContact().getPhoneNumber();
assertEquals("654", pn.getAreaCode());
assertEquals("456", pn.getPrefix());
assertEquals("4567", pn.getSuffix());
assertTrue(
trip.getDestination().startsWith("/ContactList.action"));
}
I encounter this error:
net.sourceforge.stripes.exception.StripesServletException: Unhandled exception in exception handler.
at net.sourceforge.stripes.exception.DefaultExceptionHandler.handle(DefaultExceptionHandler.java:158)
at net.sourceforge.stripes.controller.StripesFilter.doFilter(StripesFilter.java:249)
at net.sourceforge.stripes.mock.MockFilterChain.doFilter(MockFilterChain.java:63)
at net.sourceforge.stripes.mock.MockServletContext.acceptRequest(MockServletContext.java:255)
at net.sourceforge.stripes.mock.MockRoundtrip.execute(MockRoundtrip.java:195)
at net.sourceforge.stripes.mock.MockRoundtrip.execute(MockRoundtrip.java:207)
at stripesbook.test.stripesmock.ContactFormActionBeanTest.testSaveValid(ContactFormActionBeanTest.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
If I delete
trip.setParameter("contact.email", "test#test.com");
trip.setParameter("contact.phoneNumber", "654-456-4567");
I won't get any errors but will get following message from jUnit:
java.lang.AssertionError: expected:<0> but was:<1>
which seems logical.
This is my ContactFormActionBean class
public class ContactFormActionBean extends ContactBaseActionBean {
private static final String FORM="/WEB-INF/jsp/contact_form.jsp";
#DefaultHandler
public Resolution form() {
return new ForwardResolution(FORM);
}
public Resolution save() {
Contact contact = getContact();
contact.setUser(getUser());
contactDao.save(contact);
contactDao.commit();
getContext().getMessages().add(
getLocalizableMessage("contactSaved", contact)
);
return new RedirectResolution(ContactListActionBean.class);
}
#ValidationMethod(on="save")
public void validateEmailUnique(ValidationErrors errors) {
String email = getContact().getEmail();
Contact other = contactDao.findByEmail(email, getUser());
if (other != null && !other.equals(getContact())) {
errors.add("contact.email", new LocalizableError(
getClass().getName()+".contactEmailAlreadyUsed", other));
}
}
}
Why this error happens?
[ADDED]
This is my Setup() function where I configure mockServletContext before running any test functions:
...
private static MockServletContext mockServletContext;
private static MockHttpSession mockSession;
#BeforeClass
public static void setup() throws Exception {
mockServletContext = new MockServletContext("webmail");
Map<String,String> params = new HashMap<String,String>();
params.put("ActionResolver.Packages", "stripesbook.action");
params.put("Extension.Packages", "stripesbook.ext,"
+ "net.sourceforge.stripes.integration.spring");
mockServletContext.addFilter(StripesFilter.class,
"StripesFilter", params);
mockServletContext.setServlet(DispatcherServlet.class,
"DispatcherServlet", null);
mockSession = new MockHttpSession(mockServletContext);
mockServletContext.addInitParameter("contextConfigLocation",
"/WEB-INF/applicationContext-test.xml");
ContextLoaderListener springContextLoader =
new ContextLoaderListener();
springContextLoader.contextInitialized(
new ServletContextEvent(mockServletContext));
// Load mock user
MockRoundtrip trip = new MockRoundtrip(mockServletContext,
MockDataLoaderActionBean.class, mockSession);
trip.execute();
// Login mock user
trip = new MockRoundtrip(mockServletContext,
LoginActionBean.class, mockSession);
trip.setParameter("username", "freddy");
trip.setParameter("password", "nadia");
trip.execute("login");
}
...
I think there could be some config problems cause when I remove
<classpathentry kind="src" path="src/main/webapp" />
from class path I get different error :
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext-test.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext-test.xml]
There seems to be a Stripes configuration problem.
Did you configure the mockServletContext correctly?
U tried with Spring ?
I have done it with :
Object test= springContextListener.getContextLoader().getCurrentWebApplicationContext().getBean("MyActionBean");
annoted your class with : #RunWith(SpringJUnit4ClassRunner.class)
concerning org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext-test.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext-test.xml]
add :
#RunWith(SpringJUnit4ClassRunner.class to your test Class
and add Spring-test Jar to your project.
recheck the line : filterParams.put("ActionResolver.Packages", "yourapplicationpackagesPath.action");