No running JUnit tests through Gradle on command line


(max gun) #1

Help please! I’m using Gradle 4.7 on Windows 7. When I run my JUnit test the command “gradle test” The tests die with errors like below “ru.infinnity.xray.CreateConclusionServiceTest > checkContentExtUser FAILED
com.itextpdf.io.IOException at CreateConclusionServiceTest.java:32
Caused by: java.io.FileNotFoundException at CreateConclusionServiceTest.java:32”
Class CreateConclusionServiceTest use resources as image, fonts in folder "src\main\resources’.
These tests run fine when I run them through Intellij IDEA. What do I need to adjust in Gradle so that these tests run normally when I run them through a command line?
Thank’s


(nerro) #3

How you get the image file for your test?

P.S.: if you provide an example project (or link to existing one), it will be simpler and faster to find the issue.


(max gun) #4

This is tested class:
"@Service(CreateConclusionService.NAME)
public class CreateConclusionServiceBean implements CreateConclusionService {

private Logger log = LoggerFactory.getLogger(CreateConclusionServiceBean.class);

@Override
public byte[] createPdf(Research research) throws IOException {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    //Set background **Here is error**
    Image background = new Image(ImageDataFactory.create("modules/core/src/main/resources/img/blank.jpg"));

    //Stamp 
    Image stamp = new Image(ImageDataFactory.create("modules/core/src/main/resources/img/logo.png"));

    //Font
    PdfFont ru_Font = PdfFontFactory.createFont("modules/core/src/main/resources/fonts/FreeSans.ttf", PdfEncodings.IDENTITY_H, true);

    PdfWriter writer = new PdfWriter(byteArrayOutputStream);
    PdfDocument pdfDoc = new PdfDocument(writer);
    BackgroundEventHandler handler = new BackgroundEventHandler(background);
    pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);

     Document doc = new Document(pdfDoc);
    Rectangle[] rectText = {new Rectangle(10, 100, 575, 625)};
    doc.setRenderer(new ColumnDocumentRenderer(doc, rectText));
    doc.setFont(ru_Font);
    doc.setFontSize(10);
    doc.setFontColor(ColorConstants.BLACK);

  
    Paragraph pResearch = new Paragraph(research.getResearchType().getName()).setFontSize(15).setBold().setMargins(0, 0, 0, 0);
    doc.add(pResearch);

    
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    String date = dateFormat.format(research.getOpenTs());
    Paragraph pData = new Paragraph().add("Дата получения исследования:     ").add(date).setMargins(0, 0, 0, 0);
    doc.add(pData);

   
    Paragraph pNumber = new Paragraph().add("Номер исследования:     ").add(String.valueOf(research.getSeqNo())).setMargins(0, 0, 0, 0);
    doc.add(pNumber);

     String sex;
    if (String.valueOf(research.getPatientSex()).equals("Male")) {
        sex = "Male";
    } else if (String.valueOf(research.getPatientSex()).equals("Female")) {
        sex = "Female";
    } else
        sex = null;

    Paragraph pSex = new Paragraph().add("Пол:     ").add(sex).setMargins(0, 0, 0, 0);
    doc.add(pSex);
    Paragraph pAge = new Paragraph().add("Возраст:     ").add(String.valueOf(research.getPatientAgeInYears())).setMargins(0, 0, 0, 0);
    doc.add(pAge);

   Paragraph pResearchMethod = new Paragraph().add("Метод исследования:     ").add(research.getResearchMethodDescription()).setMargins(0, 0, 0, 0);
    doc.add(pResearchMethod);

    //Блок "Область исследования"
    Paragraph pAreaResearch = new Paragraph().add("Область исследования:     ").add(research.getResearchObjectDescription()).setMargins(0, 0, 0, 0);
    pAreaResearch.setWidth(570);
    doc.add(pAreaResearch);

    //Блок "Заключение"
    List<Conclusion> conclusionList = research.getConclusions();
    Paragraph pConclusion = new Paragraph().add("Заключение:     ").setMargins(0, 0, 0, 0);
    for (Conclusion conclusion : conclusionList) {
        String text = conclusion.getDescription();
        pConclusion.add(text);
        pConclusion.setWidth(570);

    }
    doc.add(pConclusion);
   
    stamp.setHeight(120).setWidth(120);
    String fullNameExpert = research.getAssignee().getFirstName() + " " + research.getAssignee().getLastName() + " " + research.getAssignee().getMiddleName();
    Text text = new Text(fullNameExpert).setTextRise(stamp.getImageScaledHeight() / 2).setFontSize(14);
    Paragraph pExpert = new Paragraph().add(text).addTabStops(new TabStop(500, TabAlignment.RIGHT)).add(new Tab()).add(stamp);
    doc.add(pExpert);
    doc.close();
    byte[] bytesDocument = byteArrayOutputStream.toByteArray();

    return bytesDocument;
}

class BackgroundEventHandler implements IEventHandler {
    protected Image img;

    public BackgroundEventHandler(Image img) {
        this.img = img;
    }

    @Override
    public void handleEvent(Event event) {

        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
        Rectangle area = page.getPageSize();
        new Canvas(canvas, pdfDoc, area).add(img);
    }
}

}
" and Test Class
"public class CreateConclusionServiceTest {

private CreateConclusionServiceBean conclusion = new CreateConclusionServiceBean();
private Research research = new Research();
private byte[] pdfData;


@Before
public void setResearch() throws IOException {

    ResearchType researchType = new ResearchType();
    researchType.setName("Рентген");

    ExtUser expert = new ExtUser();
    expert.setFirstName("Петр");
    expert.setLastName("Иванов");
    expert.setMiddleName("Николаевич");
    research.setAssignee(expert);

    research.setPatientSex(PatientSex.fromId(10));

    List<ru.infinnity.xray.entity.Conclusion> list = new ArrayList<>();
    ru.infinnity.xray.entity.Conclusion conclusion1 = new ru.infinnity.xray.entity.Conclusion();
    ru.infinnity.xray.entity.Conclusion conclusion2 = new ru.infinnity.xray.entity.Conclusion();
    conclusion1.setDescription("Отек головного мозга");
    conclusion2.setDescription("Обнаружено расширение сосудов в правой затылочной части");
    list.add(conclusion1);
    list.add(conclusion2);
    research.setConclusions(list);

    research.setOpenTs(new Date());
    research.setPatientAgeInYears(15);
    research.setResearchMethodDescription("Ультравист 300");
    research.setResearchType(researchType);
    research.setResearchObjectDescription("Голова");
    research.setSeqNo(12L);
    pdfData = conclusion.createPdf(research);

}

@Test
public void checkContentResearch() throws Exception {

    SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd  HH:mm:ss ");
    String date = df.format(research.getOpenTs());
    String expectedSeqNo = String.valueOf(research.getSeqNo());
    String expectedDate = date;
    String expectedResearchDescription = research.getResearchMethodDescription();
    String expectedResearchObject = research.getResearchObjectDescription();
    String expectedAge = String.valueOf(research.getPatientAgeInYears());

    assertThat(extractPdfText(pdfData).contains(expectedDate));
    assertThat(extractPdfText(pdfData).contains(expectedResearchDescription));
    assertThat(extractPdfText(pdfData).contains(expectedResearchObject));
    assertThat(extractPdfText(pdfData).contains(expectedSeqNo));
    assertThat(extractPdfText(pdfData).contains(expectedAge));

}

@Test
public void checkContentResearchType() throws IOException {
    String expectedResearchType = research.getResearchType().getName();

    assertThat(extractPdfText(pdfData).contains(expectedResearchType));
}

@Test
public void checkContentPatientSex() throws IOException {
    String expectedSex = "Мужской";

    assertThat(extractPdfText(pdfData).contains(expectedSex));

}

@Test
public void checkContentExtUser() throws IOException {
    String expectedExtUser = research.getAssignee().getFirstName() + " " + research.getAssignee().getLastName() + " " + research.getAssignee().getMiddleName();

    assertThat(extractPdfText(pdfData).contains(expectedExtUser));

}

@Test
public void checkContentConclusion() throws IOException {
    List<ru.infinnity.xray.entity.Conclusion> listConclusion = research.getConclusions();
    String expectedDescription = null;
    for (ru.infinnity.xray.entity.Conclusion conclusion : listConclusion) {
        String description = conclusion.getDescription();
        expectedDescription += description;
    }

    assertThat(extractPdfText(pdfData).contains(expectedDescription));

}

private static String extractPdfText(byte[] pdfData) throws IOException {
    PDDocument pdfDocument = PDDocument.load(new ByteArrayInputStream(pdfData));
    try {
        return new PDFTextStripper().getText(pdfDocument);
    } finally {
        pdfDocument.close();
    }
}

}"


(nerro) #5

try to do following:
ImageDataFactory.create(getClass().getResource("/img/blank.jpg"))
why is it so:
https://docs.oracle.com/javase/tutorial/uiswing/components/icon.html#getresource


(max gun) #7

Now even the IDE are falling. throw NPE.


(nerro) #8

can you share minimal project with your test? (it would be simpler to provide a solution).


(max gun) #9

Here is part project on GitHub test


(max gun) #10

some problem with resources, tried many ways to get resources but they are not find


(Kushal Kadaba) #11

Yeah, you need a resources folder inside test, where you put in your image. What do you get when you check the path of getClass().getResource(“img/blank.jpg”).getPath()
?


(max gun) #12

Well, it seems my difficulties came from another problem (resources not being copied to the proper places). I’m new to gradle. Something might be wrong with mine build. gradle

buildscript {
ext.cubaVersion = ‘6.8.3’
repositories {
maven {
url ‘https://repo.cuba-platform.com/content/groups/work
credentials {
username(rootProject.hasProperty(‘repoUser’) ? rootProject[‘repoUser’] : ‘cuba’)
password(rootProject.hasProperty(‘repoPass’) ? rootProject[‘repoPass’] : ‘cuba123’)
}
}

}
dependencies {
    classpath "com.haulmont.gradle:cuba-plugin:$cubaVersion"
}

}

def globalModule = project(’:app-global’)
def coreModule = project(’:app-core’)
def guiModule = project(’:app-gui’)
def webModule = project(’:app-web’)
def webThemesModule = project(’:app-web-themes’)

def servletApi = ‘org.apache.tomcat:tomcat-servlet-api:8.0.26’

apply(plugin: ‘idea’)
apply(plugin: ‘cuba’)

cuba {
artifact {
group = ‘ru.infinnity.xray’
version = ‘0.1’
isSnapshot = true
}
tomcat {
dir = “$project.rootDir/deploy/tomcat”
}
}

dependencies {
appComponent(“com.haulmont.cuba:cuba-global:$cubaVersion”)

}

def postgres = ‘org.postgresql:postgresql:9.4.1212’

configure([globalModule, coreModule, guiModule, webModule]) {
apply(plugin: ‘java’)
apply(plugin: ‘maven’)
apply(plugin: ‘idea’)
apply(plugin: ‘cuba’)

repositories {
    mavenCentral()

}
dependencies {
    testCompile('junit:junit:4.12')
    testCompile group: 'org.assertj', name: 'assertj-core', version: '3.9.1'
    testCompile('org.apache.pdfbox:pdfbox:2.0.9')
    testCompile('org.mockito:mockito-core:2.18.3')
}

task sourceJar(type: Jar) {
    from file('src')
    classifier = 'sources'
}

artifacts {
    archives sourceJar
}

}

configure(globalModule) {
buildInfo {
version = System.getenv(‘BUILD_VCS_BRANCH’) ?: ‘0.0.0’
properties = [‘changeset’: System.getenv(‘BUILD_VCS_NUMBER’) ?: ‘000000000000’]
}

dependencies {
    compile('joda-time:joda-time:2.9.9')

}
task enhance(type: CubaEnhancing)

}

configure(coreModule) {

configurations {
    jdbc
    dbscripts
}

dependencies {
    compile(globalModule)
    provided(servletApi)
    jdbc(postgres)
    testRuntime(postgres)
    compile('com.github.pengrad:java-telegram-bot-api:3.6.0')
    compile('com.itextpdf:kernel:7.1.2')
    compile('com.itextpdf:layout:7.1.2')
    compile('com.itextpdf:io:7.1.2')
    compile('joda-time:joda-time:2.9.9')

}

sourceSets {
main{
java{
srcDir(‘src’)
}
resources{
srcDirs ‘src/resources’
}
}
}
task cleanConf(description: ‘Cleans up conf directory’) {
doLast {
def dir = new File(cuba.tomcat.dir, ‘/conf/app-core’)
if (dir.isDirectory()) {
ant.delete(includeemptydirs: true) {
fileset(dir: dir, includes: ‘**/*’, excludes: ‘local.app.properties’)
}
}
}
}

task deploy(dependsOn: [assemble, cleanConf], type: CubaDeployment) {
    appName = 'app-core'
    appJars('app-global', 'app-core')
}

task createDb(dependsOn: assembleDbScripts, description: 'Creates local database', type: CubaDbCreation) {
    dbms = 'postgres'
    host = 'localhost:5432'
    dbName = 'xray'
    dbUser = 'cuba'
    dbPassword = 'cuba'
}

task updateDb(dependsOn: assembleDbScripts, description: 'Updates local database', type: CubaDbUpdate) {
    dbms = 'postgres'
    host = 'localhost:5432'
    dbName = 'xray'
    dbUser = 'cuba'
    dbPassword = 'cuba'
}

}

configure(guiModule) {
dependencies {
compile(globalModule)

}

task deployConf(type: Copy) {
    from file('src')
    include "ru/infinnity/xray/**"
    into "$cuba.tomcat.dir/conf/app"
}

}

configure(webModule) {
configurations {
webcontent
}

dependencies {
    provided(servletApi)
    compile(guiModule)


}

task webArchive(type: Zip) {
    from file("$buildDir/web")
    from file('web')
    classifier = 'web'
}

artifacts {
    archives webArchive
}

task deployConf(type: Copy) {
    from file('src')
    include "ru/infinnity/xray/**"
    into "$cuba.tomcat.dir/conf/app"
}

task clearMessagesCache(type: CubaClearMessagesCache) {
    appName = 'app'
}
deployConf.dependsOn clearMessagesCache

task cleanConf(description: 'Cleans up conf directory') {
    doLast {
        def dir = new File(cuba.tomcat.dir, '/conf/app')
        if (dir.isDirectory()) {
            ant.delete(includeemptydirs: true) {
                fileset(dir: dir, includes: '**/*', excludes: 'local.app.properties')
            }
        }
    }
}

task deploy(dependsOn: [assemble, cleanConf], type: CubaDeployment) {
    appName = 'app'
    appJars('app-global', 'app-gui', 'app-web')
}
task buildScssThemes(type: CubaWebScssThemeCreation)
task deployThemes(type: CubaDeployThemeTask, dependsOn: buildScssThemes)
assemble.dependsOn buildScssThemes

}

configure(webThemesModule) {
apply(plugin: ‘java’)
apply(plugin: ‘maven’)
apply(plugin: ‘cuba’)

appModuleType = 'web-themes'

buildDir = file('../build/scss-themes')

sourceSets {
    main {
        java {
            srcDir '.'
        }
        resources {
            srcDir '.'
        }
    }
}

}

task undeploy(type: Delete, dependsOn: ‘:app-web:cleanConf’) {
delete("$cuba.tomcat.dir/shared")
delete("$cuba.tomcat.dir/webapps/app-core")
delete("$cuba.tomcat.dir/webapps/app")
}

task restart(dependsOn: [‘stop’, ‘:app-core:deploy’, ‘:app-web:deploy’], description: ‘Redeploys applications and restarts local Tomcat’) {
doLast {
ant.waitfor(maxwait: 6, maxwaitunit: ‘second’, checkevery: 2, checkeveryunit: ‘second’) {
not {
socket(server: ‘localhost’, port: ‘8787’)
}
}
start.execute()
}
}

task wrapper(type: Wrapper) {
gradleVersion = ‘4.3.1’
}

apply from: ‘extra.gradle’

task buildWar(type: CubaWarBuilding) {
appHome = ‘${catalina.base}/app_home’
appProperties = [
‘cuba.automaticDatabaseUpdate’ : ‘true’,
‘cuba.testMode’ : ‘true’,
‘cuba.webAppUrl’ : ‘http://10.222.221.53:8080/app’,
‘cuba.web.loginDialogDefaultUser’ : ‘’,
‘cuba.web.loginDialogDefaultPassword’: ‘’,
‘xray.urlPayForResearch’ : ‘http://osod-portal/research/%s’,
‘xray.urlTrackResearch’ : ‘http://osod-portal/research/%s’,
‘xray.urlChatOnResearch’ : ‘http://osod-portal/research/%s
]
singleWar = false
includeJdbcDriver = true
hsqlInProcess = false
includeContextXml = true
coreContextXmlPath = ‘configs/core/web/META-INF/deploy-context-test.xml’
}

task buildWarProduction(type: CubaWarBuilding) {
appHome = ‘${catalina.base}/app_home’
appProperties = [
‘cuba.web.productionMode’ : ‘true’,
‘cuba.testMode’ : ‘false’,
‘cuba.automaticDatabaseUpdate’ : ‘true’,
‘cuba.webAppUrl’ : ‘http://uzr.infinnity.ru/app’,
‘cuba.web.loginDialogDefaultUser’ : ‘’,
‘cuba.web.loginDialogDefaultPassword’: ‘’,
‘cuba.email.fromAddress’ : ‘osod-mailer@infinnitysolutions.com’,
‘cuba.email.smtpPassword’ : ‘g4ea9fk9gggt’,
‘cuba.email.smtpUser’ : ‘osod-mailer@infinnitysolutions.com’,
‘cuba.fileStorageDir’ : ‘/mnt/filestorage’,
‘xray.urlPayForResearch’ : ‘http://:/…/pay?id=%s’,
‘xray.urlTrackResearch’ : ‘http://:/…/track?id=%s’,
‘xray.urlChatOnResearch’ : ‘http://:/…/chat?id=%s’
]
singleWar = false
includeJdbcDriver = true
includeContextXml = true
coreContextXmlPath = ‘configs/core/web/META-INF/deploy-context-production.xml’
}