Cannot Unit Test Using Fongo fails in 4.1.4 - worked in 3.1.4 - spring-data-mongodb

https://github.com/sanjuthomas/spring-data-mongodb
I have try several examples such as the one above to understand how to unit test mongo applications using fongo. All the examples examples worked - including the one above but when I upgrade the pom to the latest releases supported in spring boot all the examples fail. It seems the application context is no longer getting loaded for the test. Is this unit test functionality broken or do I need to change the code?
Below is the code that fails and used to work in Spring 3 - now the rule fails stating that a mongo instance does not exist in the context:
package com.ourownjava.spring.data.mongo.repository;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.foursquare.fongo.Fongo;
import com.lordofthejars.nosqlunit.annotation.ShouldMatchDataSet;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import com.mongodb.Mongo;
import com.ourownjava.spring.data.mongo.model.Trade;
/**
* Spring Data MongoDB Repository Unit testcase.
*
* #author ourownjava.com
*
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class TestTradeRepository {
#Autowired
private ApplicationContext applicationContext;
#Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb(
"trade-db");
#Autowired
private TradeRepository tradeRepository;
#Test
#ShouldMatchDataSet(location = "/testData/trade-t1.json")
public void shouldSaveTrade(){
tradeRepository.save(createTrade());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByTraderId(){
final List<Trade> trades = tradeRepository.findByTraderId("papjac");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("papjac", trades.get(0).getTraderId());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByExchangeCode(){
final List<Trade> trades = tradeRepository.findByExchangeCode("NYSE");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("NYSE", trades.get(0).getExchangeCode());
}
private Trade createTrade(){
final Trade trade = new Trade();
trade.setId("t1");
trade.setTraderId("papjac");
trade.setExchangeCode("NYSE");
trade.setValue(90.3);
return trade;
}
#Configuration
#EnableMongoRepositories
#ComponentScan(basePackageClasses = { TradeRepository.class })
static class MongoConfiguration extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "trade-db";
}
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}
#Override
protected String getMappingBasePackage() {
return "com.ourownjava.spring.data.mongo";
}
}
}

You have to use Annotation #Bean for mongo()
#Bean
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}

Related

Error:The method dataSource(DataSource) is undefined for the type EntityManagerFactoryBuilder

I am trying to connect two databases(MSSQL server and H2db) using springboot with spring data jpa and hibernate
I have created two configuration files
but getting error in configuration file.
Error:The method dataSource(DataSource) is undefined for the type EntityManagerFactoryBuilder
at return builder.dataSource(db2DataSource()) point
DbOneConfig
package com.examle.demo.config.h2db;
import java.util.HashMap;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
//to active transaction and services
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "db1EntityManagerFactory",
transactionManagerRef = "db1TransactionManager",
basePackages = { "package com.example.h2db.repo" } //for repository
)
public class DbOneConfig {
//datasource
#Bean //indicates creating the Object here
#ConfigurationProperties(prefix ="db1.datasource")
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();//build method returns the Object ,
//create method internally builds the datasource here
}
//EntityManagerFactory
#Primary
#Bean(name = "db1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean db1EntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("db1DataSource") DataSource db1DataSource
) {
//HashMap<String, Object>properties = new HashMap<>();
//properties.put("hibernate.hbm2ddl.auto","create");
//properties.put("hibernate.dialect","org.hibernate.dialect.H2Dialect");
return builder
.dataSource(db1DataSource) //getting error on this line
.packages("com.eaxample.demo.model.h2db")
.build();
}
//TXManager
#Bean
public PlatformTransactionManager db1TransactionManager(
#Qualifier("db1EntityManagerFactory")
//read object from the container
EntityManagerFactory entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
You have imported org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder and you should import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder.

replacement for camel cxfbean

we are currently struggling with updating our legacy service (non spring, jee + deltaspike, weld) and it's dependencies.
We try to upgrade from camel 2.16.2 to 3.x (due to java 11 compatibility).
We have already read through the migration guide several times, but could not find any reference to your replacement of the cxfbean component.
e.g.:
public class MonitoringRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("servlet:///monitoring?matchOnUriPrefix=true")
.to("cxfbean:monitoringService")
.setId("MonitoringRoute");
}
}
#Named("monitoringService")
public class MonitoringService implements MonitoringAPI {
#Override
public String status() {
return "OK";
}
}
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
public interface MonitoringAPI {
#GET
#Path("status")
#Produces(MediaType.TEXT_PLAIN)
String status();
}
We already tried cxfrs:monitoringService, but this will led to "Uri is not absolute" exception.
Any idea to replace cxfbean properly?

Camel exchange header lost during test

I'm trying to test the onException(JsonProcessingException.class) route in the following class (please don't mind its name, I've cut some code out for clarity):
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import pl.muni.camel.sample.customer.domain.CustomerData;
import pl.muni.camel.sample.customer.route.processor.CreateCustomerErrorResponseProcessor;
import pl.muni.camel.sample.customer.route.processor.CreateCustomerOkResponseProcessor;
#Component
public class SendCustomerDataToQueueRoute extends RouteBuilder {
#Value("${http.rest.listener.host}")
private String restListenerHost;
#Value("${http.rest.listener.port}")
private int restListenerPort;
#Override
public void configure() {
restConfiguration()
.component("restlet")
.dataFormatProperty("prettyPrint", "true")
.host(restListenerHost)
.port(restListenerPort);
rest("/rest/v1/customer")
.post("/create")
.bindingMode(RestBindingMode.json)
.skipBindingOnErrorCode(false)
.consumes("application/json")
.type(CustomerData.class)
.produces("application/json")
.route().id("acceptCreateCustomerRequest")
.from("direct:acceptRequest")
.to("direct:processRequest");
onException(JsonProcessingException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.to("direct:processException");
onException(Exception.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
.to("direct:processException");
from("direct:processRequest").routeId("processCreateCustomerRequest")
.log("Received customer data: ${body}")
.process(new CreateCustomerOkResponseProcessor()).id("createOkResponse");
from("direct:processException").routeId("processCreateCustomerException")
.log(LoggingLevel.ERROR, "${exception.stacktrace}").id("logExceptionStackTrace")
.process(new CreateCustomerErrorResponseProcessor()).id("createErrorResponse");
}
}
I want to intercept the exchange after createErrorResponse processor and run some assertions on it. So far I've come up with this code, in which I weave in a mock endpoint after direct:processException endpoint:
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringBootRunner;
import org.apache.camel.test.spring.EnableRouteCoverage;
import org.apache.camel.test.spring.MockEndpointsAndSkip;
import org.apache.camel.test.spring.UseAdviceWith;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.annotation.DirtiesContext;
import pl.muni.camel.sample.customer.infrastructure.rest.CreateCustomerResponse;
#UseAdviceWith
#MockEndpointsAndSkip("restlet*")
#EnableRouteCoverage
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
#SpringBootTest
#ComponentScan("pl.muni.camel.sample.customer")
#RunWith(CamelSpringBootRunner.class)
public class SendCustomerDataToQueueIntegrationTest {
#Produce
private ProducerTemplate producerTemplate;
#Autowired
private CamelContext context;
#EndpointInject(uri = "mock:error")
private MockEndpoint errorEndpoint;
#Before
public void setUp() throws Exception {
context.getRouteDefinition("processCreateCustomerRequest").adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() {
weaveByToUri("direct:processException")
.after()
.to("mock:error");
}
});
context.start();
}
#After
public void tearDown() throws Exception {
context.stop();
}
#Test
public void shouldReturnHttpStatus400ForInvalidJson() throws InterruptedException {
// given
final String customerDataString = "{\"firstName\": \"aaa\", \"lastname\": \"bbb\"}";
//when
producerTemplate.sendBody("direct:acceptRequest", customerDataString);
//then
errorEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 400);
errorEndpoint.assertIsSatisfied();
final List<Exchange> exchanges = errorEndpoint.getExchanges();
Assertions.assertThat(exchanges).hasSize(1);
final Exchange exchange = exchanges.get(0);
final CreateCustomerResponse response = exchange.getIn().getBody(CreateCustomerResponse.class);
Assertions.assertThat(response.isSuccess()).isFalse();
Assertions.assertThat(response.getErrorMessage()).startsWith("UnrecognizedPropertyException: Unrecognized field \"lastname\"");
}
}
Unfortunately, the Exchange.HTTP_RESPONSE_CODE header somehow disappears during the test and the assertion on errorEndpoint fails. I ran the test with debugger and breakpoint set within CreateCustomerErrorResponseProcessor class and there the header was still available.
Is there another way to set up the test and be able to retrieve the header or could this be a bug?
The URI you are weaving ("direct:processException") in your unit test is attached to a wrong route definition.
It should be:
context.getRouteDefinition("processCreateCustomerException").adviceWith(...)
(and not "processCreateCustomerRequest")

how to save data in data base table has two primary key using jpa spring boot angular js

THIS IS MY ENTITY
my probelem is i don't knwo why my http requtte dosn't work
i'm using ARC application to test the requette this is the error
"status": 500,
"error": "Internal Server Error",
"exception":"org.springframework.beans.ConversionNotSupportedException",
"message": "Failed to convert property value of type 'java.lang.Long' to required type 'com.projet.pfe.entities.AF' for property 'fa'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Long' to required type 'com.projet.pfe.entities.AF' for property 'fa': no matching editors or conversion strategy found",
"path": "/saveactaf/2/2/333"
package com.projet.pfe.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#IdClass(ActiviteAF.class)
#Entity
public class ActiviteAF implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name="idact")
private Activite activite;
#Id
#ManyToOne
#JoinColumn(name="idaf")
private AF fa;
private double montant;
public Activite getActivite() {
return activite;
}
public void setActivite(Activite activite) {
this.activite = activite;
}
public AF getFa() {
return fa;
}
public void setFa(AF fa) {
this.fa = fa;
}
public double getMontant() {
return montant;
}
public void setMontant(double montant) {
this.montant = montant;
}
public ActiviteAF(Activite activite, AF fa, double montant) {
super();
this.activite = activite;
this.fa = fa;
this.montant = montant;
}
public ActiviteAF() {
super();
}
}
this is my Repository
package com.projet.pfe.DAO;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.projet.pfe.entities.ActiviteAF;
public interface ActiviteAFRepository extends JpaRepository<ActiviteAF,Long> {
#Query("select af from ActiviteAF af where af.activite.idActivite like :x")
public Collection<ActiviteAF> activitebyid(#Param("x") Long id);
}
this is the Rest Controller
package com.projet.pfe.service;
import com.projet.pfe.DAO.AFRepository;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.projet.pfe.DAO.ActiviteAFRepository;
import com.projet.pfe.DAO.ActiviteRepository;
import com.projet.pfe.entities.AF;
import com.projet.pfe.entities.Activite;
import com.projet.pfe.entities.ActiviteAF;
import org.springframework.web.bind.annotation.PathVariable;
#RestController
public class ActAFRestService {
#Autowired
private ActiviteAFRepository actafmet;
#Autowired
private ActiviteRepository actr;
#Autowired
private AFRepository afr;
#RequestMapping(value="/saveactaf/{idact}/{idaf}/{montant}",method=RequestMethod.POST)
public ActiviteAF save(#PathVariable(name="idact")long idact,#PathVariable(name="idaf")long idaf,#PathVariable(name="montant")double montant){
Activite a = new Activite();
AF af = new AF();
a = actr.findOne(idact);
af = afr.findOne(idaf);
ActiviteAF aaf = new ActiviteAF(a,af,montant);
return actafmet.save(aaf);
}
}
I find a solution , juste make a singel. Id and change the others to a simple annotation(forign keys) , this solution work but need a test( activite,af ) in the case of adding new object .

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources