I'm trying to use Neo4j but i still have some problems. When i try to run a test to create a node, i have an exception saying that is impossible to autowired the repository interface.
this is my configuration :
build.gradle :
buildscript {
ext {
springBootVersion = '1.2.4.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath("io.spring.gradle:dependency-management-plugin:0.5.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'io.spring.dependency-management'
jar {
baseName = 'demo'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter")
testCompile("org.springframework.boot:spring-boot-starter-test")
compile 'org.springframework.data:spring-data-neo4j:3.3.0.RELEASE'
compile("org.hibernate:hibernate-validator")
compile 'org.neo4j:neo4j:2.2.3'
compile 'javax.annotation:javax.annotation-api:1.2'
}
eclipse {
classpath {
containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7'
}
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
applicationContext.xml :
<?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:context="http://www.springframework.org/schema/context"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j-3.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.****.pocneo4j.service.impl" />
<neo4j:config storeDirectory="/data"
base-package="com.****.pocneo4j.domain.entity" />
<neo4j:repositories base-package="com.****.pocneo4j.domain.repository" />
<tx:annotation-driven />
</beans>
My entity :
package com.****.pocneo4j.domain.entity;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
#NodeEntity
public class QuestionNode {
#GraphId
private Long idQuestionNode;
private int idQuestionRef;
public Long getIdQuestionNode() {
return idQuestionNode;
}
public int getIdQuestionRef() {
return idQuestionRef;
}
public void setIdQuestionRef(int idQuestionRef) {
this.idQuestionRef = idQuestionRef;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((idQuestionNode == null) ? 0 : idQuestionNode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
QuestionNode other = (QuestionNode) obj;
if (idQuestionNode == null) {
if (other.idQuestionNode != null)
return false;
} else if (!idQuestionNode.equals(other.idQuestionNode))
return false;
return true;
}
#Override
public String toString() {
return "QuestionNode [idQuestionNode=" + idQuestionNode
+ ", idQuestionRef=" + idQuestionRef + "]";
}
}
Repository
package com.****.pocneo4j.domain.repository;
import org.springframework.data.neo4j.repository.GraphRepository;
import com.****.pocneo4j.domain.entity.QuestionNode;
public interface QuestionNodeRepository extends GraphRepository<QuestionNode>{
}
My service :
package com.****.pocneo4j.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.****.pocneo4j.domain.entity.QuestionNode;
import com.****.pocneo4j.domain.repository.QuestionNodeRepository;
import com.****.pocneo4j.service.interf.QuestionNodeIService;
#Service("QuestionNodeManager")
public class QuestionNodeService implements QuestionNodeIService {
#Autowired
private QuestionNodeRepository questionNodeRepository;
#Override
public QuestionNode create(QuestionNode questionNode){
return questionNodeRepository.save(questionNode);
}
}
and here my test
package com.****.pocneo4j.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.****.pocneo4j.domain.entity.QuestionNode;
import com.****.pocneo4j.service.interf.QuestionNodeIService;
public class Test01 {
#Test
public void test() {
#SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
QuestionNodeIService questionNodeManager = (QuestionNodeIService) ctx
.getBean("QuestionNodeManager");
QuestionNode testQuestionNode = new QuestionNode();
testQuestionNode.setIdQuestionRef(90);
questionNodeManager.create(testQuestionNode);
System.out.println("NODE ID = " + testQuestionNode.getIdQuestionNode()
+ " || QUESTION REF ID = "
+ testQuestionNode.getIdQuestionRef());
}
}
Related
I am using testng 6.9.10, extentreports 3.1.5. Using maven surefire plugin and using forkcount and reuse forks , the tests running in parallel. (i.e two instances of chrome browser opening with two tests classes running in parallel as I set forkcount -> 2 and reuseforks-> true)
mvn test -Dgroups=group1
( there are two test classes belong to group1). The problem is extent report only shows the result of the last run.
I've included only the listener class in pom.xml ( not anywhere else, Not in the #beforeclass or #afterclass as part of BaseTest class)
<property>
<name>listener</name>
<value>util.listener.TestExtentListener</value>
</property>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<forkCount>2</forkCount>
<reuseForks>true</reuseForks>
Any solution please?
public class ExtentManager {
private static ExtentReports extent;
private static String reportFileName = "Test-Automaton-Report"+".html";
private static String fileSeperator = System.getProperty("file.separator");
private static String reportFilepath = System.getProperty("user.dir") +fileSeperator+ "TestReport";
private static String reportFileLocation = reportFilepath +fileSeperator+ reportFileName;
public static ExtentReports getInstance() {
if (extent == null)
createInstance();
return extent;
}
//Create an extent report instance
public static ExtentReports createInstance() {
String fileName = getReportPath(reportFilepath);
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(reportFileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(reportFileName);
htmlReporter.config().setTimeStampFormat("EEEE, MMMM dd, yyyy, hh:mm a '('zzz')'");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
//Set environment details
extent.setSystemInfo("OS", "Mac");
extent.setSystemInfo("AUT", "QA");
return extent;
}
//Create the report path
private static String getReportPath (String path) {
File testDirectory = new File(path);
if (!testDirectory.exists()) {
if (testDirectory.mkdir()) {
System.out.println("Directory: " + path + " is created!" );
return reportFileLocation;
} else {
System.out.println("Failed to create directory: " + path);
return System.getProperty("user.dir");
}
} else {
System.out.println("Directory already exists: " + path);
}
return reportFileLocation;
}
}
public class ExtentTestManager {
static Map<Integer, ExtentTest> extentTestMap = new HashMap<Integer, ExtentTest>();
static ExtentReports extent = ExtentManager.getInstance();
public static synchronized ExtentTest getTest() {
return (ExtentTest) extentTestMap.get((int) (long) (Thread.currentThread().getId()));
}
public static synchronized void endTest() {
extent.flush();
}
public static synchronized ExtentTest startTest(String testName) {
ExtentTest test = extent.createTest(testName);
extentTestMap.put((int) (long) (Thread.currentThread().getId()), test);
return test;
}
}
public class TestExtentListener implements ITestListener {
ExtentTest test;
private static ThreadLocal<ExtentTest> extentTestThreadLocal = new ThreadLocal<ExtentTest>();
public void onStart(ITestContext context) {
System.out.println("*** Test Suite " + context.getName() + " started ***");
}
public void onFinish(ITestContext context) {
System.out.println(("*** Test Suite " + context.getName() + " ending ***"));
ExtentTestManager.endTest();
ExtentManager.getInstance().flush();
}
public void onTestStart(ITestResult result) {
System.out.println(("*** Running test method " + result.getMethod().getMethodName() + "..."));
test = ExtentTestManager.startTest(result.getMethod().getMethodName());
extentTestThreadLocal.set(test);
}
public void onTestSuccess(ITestResult result) {
System.out.println("*** Executed " + result.getMethod().getMethodName() + " test successfully...");
extentTestThreadLocal.get().log(Status.PASS, "Test passed");
}
public void onTestFailure(ITestResult result) {
System.out.println("*** Test execution " + result.getMethod().getMethodName() + " failed...");
extentTestThreadLocal.get().log(Status.FAIL, "Test Failed");
}
public void onTestSkipped(ITestResult result) {
System.out.println("*** Test " + result.getMethod().getMethodName() + " skipped...");
extentTestThreadLocal.get().log(Status.SKIP, "Test Skipped");
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
System.out.println("*** Test failed but within percentage % " + result.getMethod().getMethodName());
}
}
you might not be using thread local class in java to make extent report thread safe. Otherwise objects will get overridden and extent report only shows the active tests results.
You can do something like this:
ExtentReports extent = ExtentReportGenerator.ExtentReport();
ExtentTest test;;
private static ThreadLocal<ExtentTest> extent_test = new ThreadLocal<ExtentTest>();
For more details, you can refer to this blog.
https://www.automationinja.com/post/thread-safe-extent-report-in-selenium
If you use xml file to your testclasses all report will appear in extent report
This is my XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TC_WorldAirFares Automation Test Suite">
<listeners>
<listener class-name="ExtentReports.ExtentReporterNG" />
</listeners>
<suite name="Suite" parallel="instances" thread-count="2">
<test name="TC Automation Test Suite">
<classes>
<class name="Footerlinks" />
<class name="HeaderLinks" />
<class name="BookYourFlightsNow" />
</classes>
</test>
</suite>
keep class for extentreports
here extent report class (XML file listen your extentreport class and generate reports for you test classes
package ExtentReports;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class ExtentReporterNG implements IReporter {
private ExtentReports extent;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites,
String outputDirectory) {
extent = new ExtentReports(outputDirectory + File.separator
+ "Extent.html", true);
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}
private void buildTestNodes(IResultMap tests, LogStatus status) {
ExtentTest test;
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.startTest(result.getMethod().getMethodName());
test.setStartedTime(getTime(result.getStartMillis()));
test.setEndedTime(getTime(result.getEndMillis()));
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
} else {
test.log(status, "Test " + status.toString().toLowerCase()
+ "ed");
}
extent.endTest(test);
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
The version of the gradle is 6.3-all. And here is my build.gradle:
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.72'
}
group 'com.dennis'
version '1.0-SNAPSHOT'
repositories {
mavenLocal()
mavenCentral()
}
jar {
from {
configurations.runtime.collect { zipTree(it) }
}
manifest {
attributes 'Main-Class': 'com.dennis.tcp.robot.RobotClient'
}
}
dependencies {
/*...*/
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
And here is settings.gradle
rootProject.name = 'robot'
And here is the main class:
package com.dennis.tcp.robot;
/*import ignored*/
public class RobotClient {
private static final String URL = "192.168.10.140";
private static final int PORT = 9760;
public static void main(String[] args) {
NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE,true)
.handler(new RobotClientInitializer());
ChannelFuture future = bootstrap.connect(URL, PORT).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
group.shutdownGracefully();
}
}
}
The packaging progress went well but the output jar cannot be executed and give the Exception of no main class
The jar file shows the main class RobotClient is compiled indeed. However, the java -jar cannot execute or find the mainclass.
Why did this happend?
I am trying to run and debug JUnit 5 Tests that use Mapstruct using both Visual Studio Code and Eclipse, but with no luck.
What works is to run the Test goal on Gradle. It runs the tests properly and show a result but when I try to run or debug the same test "manually" using the IDE, it throws an exception, always related to not being able to find the Mapper implementations or not being able to Autowire the clases, etc.
I have tried different things but with similar results, such as Autowire the Mapper, creating an instance of the Mapper in a method using #Before annotation... but always with no success.
Here is an example of a Mapper:
AddressMapper.java
package com.myorg.ccr.simulator.b2b.mapping;
import com.myorg.myproject.model.AddressDTO;
import com.myorg.myproject.model.StateDTO;
import com.myorg.xsd.b2b.upsertcustomer.Address;
import org.mapstruct.AfterMapping;
import org.mapstruct.BeanMapping;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
#Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE,
unmappedSourcePolicy = ReportingPolicy.IGNORE,
uses = {DateMapper.class, UUIDMapper.class, StateMapper.class})
public interface AddressMapper {
AddressMapper INSTANCE = Mappers.getMapper(AddressMapper.class);
#BeanMapping(ignoreByDefault = true)
#Mapping(target = "externalAddressId", source = "externalAddressId")
#Mapping(target = "street1", source = "streetAddress")
#Mapping(target = "street2", source = "streetAddress2")
#Mapping(target = "postOfficeBox", source = "POBox")
#Mapping(target = "city", source = "city")
#Mapping(target = "postalCode", source = "postalCode")
#Mapping(target = "salutation", source = "recipientSalutation")
#Mapping(target = "phone", source = "recipientPhone")
#Mapping(target = "comments", source = "comments")
AddressDTO addressToAddressDTO(Address address);
#InheritInverseConfiguration
Address addressDTOToAddress(AddressDTO address);
#AfterMapping
default void setStatus(Address address, #MappingTarget AddressDTO addressDTO) {
StateDTO state = StateMapper.INSTANCE.addressToState(address);
addressDTO.setStatus(state);
}
#AfterMapping
default void setSourceCreatedUpdatedDate(Address address, #MappingTarget AddressDTO addressDTO) {
if (address != null) {
addressDTO.setSourceCreatedDate(DateMapper.asDate(address.getSourceCreatedDate()));
addressDTO.setSourceUpdatedDate(DateMapper.asDate(address.getSourceUpdatedDate()));
}
}
#AfterMapping
default void useTypeToAddressNumber(Address address, #MappingTarget AddressDTO addressDTO) {
if (address != null && address.getType() != null && !address.getType().isEmpty()) {
switch (address.getType()) {
case "Billing":
addressDTO.setAddressNumber(1);
break;
case "Delivery":
addressDTO.setAddressNumber(2);
break;
case "Packing Station":
addressDTO.setAddressNumber(3);
break;
case "Post Office":
addressDTO.setAddressNumber(4);
break;
default:
addressDTO.setAddressNumber(null);
}
}
}
#AfterMapping
default void addressNumberToType(AddressDTO addressDTO, #MappingTarget Address address) {
if (addressDTO != null && addressDTO.getAddressNumber() != null) {
switch (addressDTO.getAddressNumber()) {
case 1:
address.setPrimaryFlag("Y");
address.setType("Billing");
break;
case 2:
address.setPrimaryFlag("N");
address.setType("Delivery");
break;
case 3:
address.setPrimaryFlag("N");
address.setType("Packing Station");
break;
case 4:
address.setPrimaryFlag("N");
address.setType("Post Office");
break;
default:
address.setPrimaryFlag("N");
address.setType(null);
}
}
}
#AfterMapping
default void contactFullname(Address address, #MappingTarget AddressDTO addressDTO) {
String firstName = address.getRecipientFirstName();
String lastName = address.getRecipientLastName();
if (firstName != null && !firstName.isEmpty() && lastName != null && !lastName.isEmpty()) {
addressDTO.setContactFullname(firstName + " " + lastName);
} else if ((firstName == null || firstName.isEmpty()) && lastName != null && !lastName.isEmpty()) {
addressDTO.setContactFullname(lastName);
} else if (firstName != null && !firstName.isEmpty() && (lastName == null || lastName.isEmpty())) {
addressDTO.setContactFullname(firstName);
}
}
#AfterMapping
default void addressRecipientName(AddressDTO addressDTO, #MappingTarget Address address) {
if (addressDTO != null && addressDTO.getContactFullname() != null && !addressDTO.getContactFullname().isEmpty()) {
address.setRecipientFirstName(addressDTO.getContactFullname());
}
}
#AfterMapping
default void setActiveFlag(AddressDTO addressDTO, #MappingTarget Address address) {
String activeFlag = "N";
if (addressDTO != null) {
activeFlag = StateMapper.INSTANCE.stateToActiveFlag(addressDTO.getStatus());
}
address.setActiveFlag(activeFlag);
}
#AfterMapping
default void setDeletedFlag(AddressDTO addressDTO, #MappingTarget Address address) {
String deletedFlag = "N";
if (addressDTO != null) {
deletedFlag = StateMapper.INSTANCE.stateToDeletedFlag(addressDTO.getStatus());
}
address.setDeletedFlag(deletedFlag);
}
#AfterMapping
default void setCountry(AddressDTO addressDTO, #MappingTarget Address address) {
String country = null;
if (addressDTO != null && addressDTO.getCountry() != null && !addressDTO.getCountry().isEmpty()) {
country = addressDTO.getCountry();
}
address.setISOCountryCode(country);
}
}
Here is an example of a Test:
AddressMapperTest.java
package com.myorg.ccr.simulator.b2b.messaging.mapping;
import com.myorg.myproject.model.AddressDTO;
import com.myorg.myproject.model.StateDTO;
import com.myorg.ccr.simulator.b2b.mapping.AddressMapper;
import com.myorg.ccr.simulator.b2b.messaging.mapping.helpers.AddressMappingHelper;
import com.myorg.xsd.b2b.upsertcustomer.Address;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import static org.assertj.core.api.Assertions.assertThat;
#ExtendWith(SpringExtension.class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class AddressMapperTest {
private AddressMapper mapper = AddressMapper.INSTANCE;
#Test
public void xsdAddressToAddressTest() {
Address xsdAddress = new Address();
xsdAddress.setActiveFlag("Y");
xsdAddress.setDeletedFlag("N");
xsdAddress.setType("Billing");
xsdAddress.setPrimaryFlag("N");
xsdAddress.setExternalAddressId("15106794");
xsdAddress.setStreetAddress("Some Street Name 70 E/24");
xsdAddress.setStreetAddress2("Some Building info 123");
xsdAddress.setPOBox("08905");
xsdAddress.setCity("Białystok");
xsdAddress.setPostalCode("15-181");
xsdAddress.setISOCountryCode("PL");
xsdAddress.setRecipientLastName("Mustermann");
xsdAddress.setRecipientFirstName("Max");
xsdAddress.setRecipientSalutation("Mr.");
xsdAddress.setRecipientPhone("512341234");
xsdAddress.setAddressInvalidFlag("Y");
xsdAddress.setComments("A comment from the user.");
xsdAddress.setSourceCreatedDate("2016-06-14T21:19:33+02:00");
xsdAddress.setSourceUpdatedDate("2019-09-05T11:26:20+02:00");
AddressDTO address = mapper.addressToAddressDTO(xsdAddress);
assertThat(address.getId()).isNull();
assertThat(address.getStatus()).isNotNull();
assertThat(address.getStatus().getValue()).isNotNull();
assertThat(address.getStatus().getValue()).isEqualTo(1);
assertThat(address.getExternalAddressId()).isEqualTo("15106794");
assertThat(address.getAddressNumber()).isEqualTo(1);
assertThat(address.getStreet1()).isEqualTo("Some Street Name 70 E/24");
assertThat(address.getStreet2()).isEqualTo("Some Building info 123");
assertThat(address.getCity()).isEqualTo("Białystok");
assertThat(address.getPostalCode()).isEqualTo("15-181");
assertThat(address.getPostOfficeBox()).isEqualTo("08905");
assertThat(address.getCountry()).isNull(); //This may change
assertThat(address.getContactFullname()).isEqualTo("Max Mustermann");
assertThat(address.getSalutation()).isEqualTo("Mr.");
assertThat(address.getPhone()).isEqualTo("512341234");
assertThat(address.getComments()).isEqualTo("A comment from the user.");
assertThat(address.getSourceCreatedDate()).isEqualTo(OffsetDateTime.parse("2016-06-14T21:19:33+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
assertThat(address.getSourceUpdatedDate()).isEqualTo(OffsetDateTime.parse("2019-09-05T11:26:20+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
#Test
public void addressDTOToXSDAddressTest() {
AddressDTO addressDTO = new AddressDTO();
StateDTO state = new StateDTO();
state.setValue(1);
addressDTO.setStatus(state);
addressDTO.setExternalAddressId("15106794");
addressDTO.setAddressNumber(1);
addressDTO.setStreet1("Some Street Name 70 E/24");
addressDTO.setStreet2("Some Building info 123");
addressDTO.setPostOfficeBox("08905");
addressDTO.setCity("Białystok");
addressDTO.setPostalCode("15-181");
addressDTO.setCountry("PL");
addressDTO.setContactFullname("Max Mustermann");
addressDTO.setSalutation("Mr.");
addressDTO.setPhone("512341234");
addressDTO.setComments("A comment from the user.");
addressDTO.setSourceCreatedDate(OffsetDateTime.parse("2016-06-14T21:19:33+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
addressDTO.setSourceUpdatedDate(OffsetDateTime.parse("2019-09-05T11:26:20+02:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME));
Address address = mapper.addressDTOToAddress(addressDTO);
assertThat(address.getActiveFlag()).isEqualTo("Y"); //This may change
assertThat(address.getDeletedFlag()).isEqualTo("N"); //This may change
assertThat(address.getExternalAddressId()).isEqualTo("15106794");
assertThat(address.getPrimaryFlag()).isEqualTo("Y");
assertThat(address.getStreetAddress()).isEqualTo("Some Street Name 70 E/24");
assertThat(address.getStreetAddress2()).isEqualTo("Some Building info 123");
assertThat(address.getCity()).isEqualTo("Białystok");
assertThat(address.getPostalCode()).isEqualTo("15-181");
assertThat(address.getPOBox()).isEqualTo("08905");
assertThat(address.getISOCountryCode()).isEqualTo("PL"); //This may change
assertThat(address.getRecipientFirstName()).isEqualTo("Max Mustermann");
assertThat(address.getRecipientSalutation()).isEqualTo("Mr.");
assertThat(address.getRecipientPhone()).isEqualTo("512341234");
assertThat(address.getComments()).isEqualTo("A comment from the user.");
assertThat(address.getSourceCreatedDate()).isEqualTo("2016-06-14T21:19:33+02:00");
assertThat(address.getSourceUpdatedDate()).isEqualTo("2019-09-05T11:26:20+02:00");
}
#Test
public void dynamicXSDAddressToAddressDTOTest() {
AddressMappingHelper mappingHelper = new AddressMappingHelper();
while (mappingHelper.hasNext()) {
mappingHelper.nextXSDAddress();
Address xsdAddress = mappingHelper.getExpectedAddress();
AddressDTO address = mapper.addressToAddressDTO(xsdAddress);
AddressDTO expectedAddress = mappingHelper.getExpectedAddressDTO();
assertThat(address).usingRecursiveComparison().isEqualTo(expectedAddress);
}
}
#Test
public void dynamicAddressDTOToXSDAddressTest() {
AddressMappingHelper mappingHelper = new AddressMappingHelper();
while (mappingHelper.hasNext()) {
mappingHelper.nextXSDAddress();
AddressDTO addressDTO = mappingHelper.getExpectedAddressDTO();
Address address = mapper.addressDTOToAddress(addressDTO);
Address expectedAddress = mappingHelper.getExpectedAddressFromDTO();
System.out.println(address);
System.out.println(expectedAddress);
assertThat(address).usingRecursiveComparison().isEqualTo(expectedAddress);
}
}
}
Here is the build.gradle file:
build.gradle
buildscript {
ext {
springBootVersion = '2.1.5.RELEASE'
jmsVersion = '2.0.1'
jaxbApiVersion = '2.2.7'
flywayVersion = '5.2.1'
// tests
junitJuniper = '5.1.1'
junitGradlePlatformVersion = '1.1.0'
assertJCoreVersion = '3.14.0'
mapstructVersion = "1.3.0.Final"
swaggerCodgenVersion = '3.0.13'
jacksonThreetenVersion = '2.6.4'
}
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
}
}
apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: "checkstyle"
group = 'com.myorg.ccr'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
repositories {
mavenCentral()
maven {
credentials {
username = "$mavenUser"
password = "$mavenPassword"
}
url "https://myorg.jfrog.io/myorg/libs-snapshot"
}
maven {
credentials {
username = "$mavenUser"
password = "$mavenPassword"
}
url "https://myorg.jfrog.io/myorg/libs-release"
}
}
sourceSets {
main {
java {
srcDir 'src/schema'
}
}
}
configurations {
jaxb_generateSources
}
dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.6'
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: springBootVersion
// https://mvnrepository.com/artifact/javax.jms/javax.jms-api
implementation group: 'javax.jms', name: 'javax.jms-api', version: jmsVersion
implementation group: 'org.springframework', name: 'spring-jms', version: '5.1.9.RELEASE'
implementation group: 'com.tibco', name: 'tibjms', version: '8.2.1'
implementation group: 'com.myorg.ccr.client', name: 'customer-client', version: '1.1.0-SNAPSHOT'
compile group: 'com.myorg.login', name: 'login-lib-java-spring', version: '1.5.0-SNAPSHOT'
runtimeOnly group: 'org.postgresql', name: 'postgresql'
runtimeOnly group: 'com.h2database', name: 'h2'
implementation group: 'org.flywaydb', name: 'flyway-core', version: flywayVersion
testImplementation "org.junit.jupiter:junit-jupiter-api:$junitJuniper"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitJuniper"
testCompile "org.assertj:assertj-core:$assertJCoreVersion"
testCompile("org.springframework.boot:spring-boot-starter-test")
testCompile("org.springframework.security:spring-security-test")
jaxb_generateSources(
[group: 'com.sun.xml.bind', name: 'jaxb-xjc', version: jaxbApiVersion],
[group: 'com.sun.xml.bind', name: 'jaxb-impl', version: jaxbApiVersion],
)
compileOnly 'org.projectlombok:lombok:1.18.6'
compileOnly "org.springframework.boot:spring-boot-configuration-processor"
implementation "org.mapstruct:mapstruct:${mapstructVersion}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
// If you are using mapstruct in test code
testAnnotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
compile "io.swagger.codegen.v3:swagger-codegen-maven-plugin:$swaggerCodgenVersion"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jacksonThreetenVersion"
}
clean {
delete 'src/schema'
}
task jaxb_generateSources {
System.setProperty('javax.xml.accessExternalSchema', 'all')
def jaxbTargetDir = file("src/schema")
doLast {
ext.generateSources = { packageName, xsdSchemaLocation ->
ant.taskdef(
name: 'xjc',
classname: 'com.sun.tools.xjc.XJCTask',
classpath: configurations.jaxb_generateSources.asPath
)
ant.jaxbTargetDir = jaxbTargetDir
ant.xjc(
destdir: '${jaxbTargetDir}',
package: packageName,
schema: xsdSchemaLocation,
encoding: 'UTF-8'
)
}
jaxbTargetDir.mkdirs()
// b2c
generateSources('com.myorg.xsd.upsertcustomer', 'src/main/resources/b2c.xsd/doAsyncUpsertCustomer_BDM_DST.xsd')
// b2b
generateSources('com.myorg.xsd.b2b.upsertcustomer', 'src/main/resources/b2b/xsd/doAsyncUpsertAccount_BDM_DST.xsd')
}
}
compileJava {
dependsOn jaxb_generateSources
}
test {
useJUnitPlatform()
// TODO: Is actual an integration and no unit test
exclude '**/ContactControllerTest.class'
}
task integrationTest(type: Test) {
useJUnitPlatform()
description = 'Runs the integration tests.'
group = 'verification'
include '**/ContactControllerTest.class'
}
tasks.withType(Checkstyle) {
exclude '**/b2bkam/**'
}
checkstyle {
config = rootProject.resources.text.fromFile("${rootDir}/config/checkstyle/checkstyle_ccr-simulator_v1.xml")
toolVersion '8.11'
}
Thank you in advance,
Aitor
I am writing a basic unit test that checks whether the returned query (type DataVersion) is not null. I have to make sure that I am using Fongo for testing my db.
This is the repo class:
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
#Autowired
MongoOperations mongoOperations;
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion findByDBAndCollection(String dbName, String collectionName) {
Criteria criteria = Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName);
Query query = Query.query(criteria);
return mongoOperations.findOne(query, DataVersion.class);
}
}
This is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
#Autowired
private DataVersionDaoMongo dataVersionDaoMongo;
#Autowired
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"));
DataVersion dataVersion = new DataVersion();
dataVersion.setDbName("DBDataVersion");
dataVersion.setVersion("version1");
dataVersion.setCollectionName("DataVersion");
mongoOperations.insert(dataVersion);**strong text**
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}
Here is the DataVersion class:
#Document(collection = "DataVersion")
public class DataVersion {
#Id
private String id;
private String dbName;
private String collectionName;
private String version;
private boolean isCompleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public boolean isCompleted() {
return isCompleted;
}
public void setCompleted(boolean isCompleted) {
this.isCompleted = isCompleted;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((collectionName == null) ? 0 : collectionName.hashCode());
result = prime * result + ((dbName == null) ? 0 : dbName.hashCode());
result = prime * result + (isCompleted ? 1231 : 1237);
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DataVersion other = (DataVersion) obj;
if (collectionName == null) {
if (other.collectionName != null)
return false;
} else if (!collectionName.equals(other.collectionName))
return false;
if (dbName == null) {
if (other.dbName != null)
return false;
} else if (!dbName.equals(other.dbName))
return false;
if (isCompleted != other.isCompleted)
return false;
if (version == null) {
if (other.version != null)
return false;
} else if (!version.equals(other.version))
return false;
return true;
}
}
This is testApplicationContext 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>
Although my unit test is passing because I declared dataVersion variable and set the values such as DbName, Version, CollectionName inside my test and calls the method findByDBandCollection. But I am not making use of Fongo DB here and I want to make use of it. How can I go about and make use of Fongo db in my test and use assertThat so that the DataVersion returned by calling findByDBAndCollection method is not null?
I created an example which illustrates that.
I'm trying to write an maven-enforcer rule, which checks that that project uses dependency management.
But I've got trouble to get the version which is written in the current project's pom.xml. I thought DependencyNode#getPremanagedVersion() would provide it, but it looks like it's returning a version which is set by a dependency (i.e. log4j is set in jbossall-client).
How can I get a dependency's version in the current pom.xml?
package org.example;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.opencredo.maven.plugins.enforcer.utils.DefaultDependencyTreePrinter;
import com.oneandone.access.preclearing.AbstractNonCacheableEnforcerRule;
public class ForceDependencyManagement extends AbstractNonCacheableEnforcerRule implements EnforcerRule {
private String message = "";
private MavenProject project;
private ArtifactRepository localRepository;
private ArtifactFactory artifactFactory;
private ArtifactMetadataSource artifactMetadataSource;
private ArtifactCollector artifactCollector;
private DependencyTreeBuilder dependencyTreeBuilder;
private void init(EnforcerRuleHelper helper) throws EnforcerRuleException {
try {
project = (MavenProject) helper.evaluate("${project}");
localRepository = (ArtifactRepository) helper.evaluate("${localRepository}");
artifactFactory = (ArtifactFactory) helper.getComponent(ArtifactFactory.class);
artifactCollector = (ArtifactCollector) helper.getComponent(ArtifactCollector.class);
artifactMetadataSource = (ArtifactMetadataSource) helper.getComponent(ArtifactMetadataSource.class);
dependencyTreeBuilder = (DependencyTreeBuilder) helper.getComponent(DependencyTreeBuilder.class);
} catch (Exception eee) {
throw new EnforcerRuleException("Unable to retrieve the rule dependencies: ", eee);
}
}
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
init(helper);
DependencyNode rootNode = buildDependencyTree();
if (rootNode != null) {
Set found = new HashSet();
Iterator iter = rootNode.iterator();
System.out.println("Dependencies: ");
while (iter.hasNext()) {
DependencyNode node = (DependencyNode) iter.next();
if (StringUtils.isNotEmpty(node.getPremanagedVersion())) {
found.add(node);
}
}
if (found.size() > 0) {
fail(found);
}
}
}
protected DependencyNode buildDependencyTree() {
try {
DependencyNode rootNode =
dependencyTreeBuilder.buildDependencyTree(project, localRepository, artifactFactory,
artifactMetadataSource, null, artifactCollector);
return rootNode;
} catch (Exception e) {
throw new RuntimeException("Failed to build dependency tree", e);
}
}
private void fail(Set found) throws EnforcerRuleException {
Iterator iter;
StringBuffer fullMessage = new StringBuffer();
if (StringUtils.isNotEmpty(message)) {
fullMessage.append(message);
} else {
fullMessage.append("Found artifact without dependency management:");
}
fullMessage.append("\n");
iter = found.iterator();
while (iter.hasNext()) {
DependencyNode node = (DependencyNode) iter.next();
Artifact artifact = node.getArtifact();
fullMessage.append(" " + artifact.getGroupId() + ":" + artifact.getArtifactId() + " is set to version "
+ node.getPremanagedVersion() + "\n");
getTreePrinter().printDependencyTree(fullMessage, artifact, 4);
}
throw new EnforcerRuleException(fullMessage.toString());
}
private DefaultDependencyTreePrinter getTreePrinter() {
return new DefaultDependencyTreePrinter(project, localRepository, artifactFactory, artifactMetadataSource,
artifactCollector, dependencyTreeBuilder);
}
public boolean isCacheable() {
return false;
}
public String getCacheId() {
return null;
}
public boolean isResultValid(EnforcerRule cachedRule) {
return false;
}
}
This should do it
MavenProject project = (MavenProject) helper.evaluate("${project}");
List dependencies = project.getDependencies();
From there just iterate throught the list of dependencies and call .getVersion()
for (int i = 0; i < project.getDependencies().size(); i++) {
String version = project.getDependencies().get(i).getVersion();
}
You can also get to the dependency management info from the project object