Test iText Java application with Groovy - java

I developed a JAVA (JDK1.6) application to manage PDF file with iText (v5.5.0).
After I wrote test application using groovy, but when i create a PdfReader object, in my test case,
PdfReader pdfReader = new PdfReader("/my/path/project/test.pdf")
I obtain the following error:
java.lang.NoClassDefFoundError: org/bouncycastle/cms/RecipientId
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2484)
...
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.cms.RecipientId
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
The first asserts in groovy test class works fine.
I created the same test class with JUnit4, and all works fine!
How can I fix the error in groovy test class?
I don't use bouncycastle class, why have I that ClassNotFound Exception?
EDIT:
GroovyTestCase
class PdfMergeItextTest extends GroovyTestCase {
PdfMergeItext pdfMerge
void setUp() {
super.setUp();
println "Test class [PdfMergeItext] avviato..."
pdfMerge = new PdfMergeItext()
pdfMerge.openOutputPdf("/my/path/project/output.pdf")
}
void tearDown() {
println "Test class [PdfMergeItext] END."
}
#Test
void testMergeSinglePdfFile() {
println "Test one Pdf.."
File outputPdf = new File("/my/path/project/output.pdf")
assertTrue outputPdf.exists()
PdfReader pdfReader = new PdfReader("/my/path/project/test.pdf")
pdfMerge.addPdf(pdfReader)
pdfMerge.flush()
pdfMerge.close()
assert outputPdf.size() > 0
println "File size: ${outputPdf.size()}"
println "End test one Pdf"
}
}
JUnit4 TestCase
public class PdfMergeItextUnitTest {
PdfMergeItext pdfMergeItext = null;
#Before
public void setUp() throws Exception {
System.out.println("Start..");
this.pdfMergeItext = new PdfMergeItext();
this.pdfMergeItext.openOutputPdf("/my/path/project/output.pdf");
}
#After
public void tearDown() throws Exception {
System.out.println("END!");
}
#Test
public void testMergePdfFile() throws IOException, BadPdfFormatException {
File outputPdf = new File("/my/path/project/output.pdf");
Assert.assertTrue(outputPdf.exists());
PdfReader pdfReader = new PdfReader("/my/path/project/test.pdf");
this.pdfMergeItext.addPdf(pdfReader);
this.pdfMergeItext.flush();
this.pdfMergeItext.close();
Assert.assertTrue(outputPdf.size() > 0);
}
}
Thanks

The BounceCastle JARs are optional, see the pom.xml (search for dependency). So, if you didn't include them in your pom.xml or build.gradle , you won't get them (anyway, what build tool are you using)?
So if you are using dependency management I understand why it is not there. The real question is: why is it needed in the first test and not in the second test?
Please make the tests totally equalent (you are calling addPdf once vs. twice and you are calling length vs. size
Since BounceCastle is used for decryption, are you testing with the same PDF file?

Related

JUnit testing deletion of a text file using a testing text file

I am trying to write a JUnit test for a java code that with three methods.
FileDeletion.java:
public static void fileDeletion(String filePath) {
File file = new File(filePath);
file.delete();
}
I looked online on how to test this, but it came up with how to make a temporary file in JUnit which is "guaranteed to be deleted after the test finishes".
See: https://howtodoinjava.com/junit/junit-creating-temporary-filefolder-using-temporaryfolder-rule/
How do I make a file which can be created and then subsequently deleted in a JUnit Test?
Any help would go a long way, many thanks.
I would consider using JUnit's TemporaryFolder rule to help you set up the file and directory structure you need for your test which is cleaned up after your test.
public class DeleteFileTest {
#Rule
public TemporaryFolder folder = new TemporaryFolder();
#Test
public void test() {
final File file = folder.newFile("myfile1.txt");
file.delete();
//Assert
}
}

TemporaryFolder not being deleted using JUnit #Rule

I'm using a temporary folder in my unit test using the #Rule of JUnit.
The folder is not being deleted after the tests finish
Java version : 1.8
JUnit version: 4.12
Os windows 10
I'm creating a file.csv under a temp folder in order to edit it using CSVPrinter from org.apache.commons
public class MyService {
public void createCSVFile(String basePath) {
try (FileWriter out = new FileWriter(format("%s/file.csv", basePath));
CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(HEADERS))) {
//printer.PrintRecord(args);
} catch (IOException e) {
log.error("Failed to create file.csv under " + basePath, e);
}
}
}
The test:
#Rule
public TemporaryFolder folder = new TemporaryFolder();
private String folderPath;
private MyService myService;
#Before
public void setup() throws IOException {
folder.newFile("file.csv");
folderPath = folder.getRoot().getPath();
}
#Test
public void testing_myService() {
myService.createCSVFile(folderPath);
//Assert
}
When i open the folder ex: C:\Users\me\AppData\Local\Temp\junit2290989758736528709
I can still see the file.csv as it was not deleted
I tried to migrate the create of the file to become in the tests. It did not fix it
#Test
public void testing_myService() {
folder.newFile("file.csv");
myService.createCSVFile(folder.getRoot().getPath());
//Assert
}
I added an #After method to delete the folder
#After
public void cleanup() throws IOException {
//Tried several ways to delete the folder and file as well
//FileUtils.forceDelete(folder.getRoot().getAbsoluteFile());
//folder.getRoot().delete();
//FileUtils.deleteDirectory(folder.getRoot());
//new File(folderPath +"/file.csv").delete();
//All methods did not delete neither the direcotry (with exception can't delete file.csv) nor deleted the file.csv
}
I also tried to call the folder.create(); and folder.delete(); myself without using the #Rule
But the folder wasn't deleted as well
The file.csv and folder are marked as read-only when viewing the properties on windows
I tried to change that in the code
folder.setWritable(true);
folder.setReadable(true);
folder.setExecutable(true);
Didn't manage to delete the folder as well
My aim is to find a solution that works for any environment where the code is checked out ex: CI pipeline on a linux server and on windows
any other reason for this behavior?
I suspect that some code is holding a file handle, preventing the temporary directory from being deleted.
I suggest:
#Rule
public final TemporaryFolder folder = TemporaryFolder.builder()
.assureDeletion()
.build();
That should cause TemporaryFolder to throw an exception if it could not delete the folder.
You should probably be creating and deleting in a folder within your project structure.
But it's probably not working because of a permission issue:
Either change the permissions of the folder so that the program has priveledges to delete, or run the program/IDE as an administrator.
That should fix the problem.

JUnit Testing in Netbeans 8.1

I have been working on a Java Application [That uses Servlets, etc]. And I was hoping to run JUnit Testing for my Controller methods. However, after adding the libraries of JUnit 4.12 and Hamcrest 1.3 & generating the test cases using NetBeans on my controllers. I have faced this problem when I ran the test.
Testsuite: controller.AccountControllerTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0 sec
Testcase: controller.AccountControllerTest:BeforeFirstTest: Caused an ERROR
null
junit.framework.AssertionFailedError
at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
Test controller.AccountControllerTest FAILED (crashed)
I have not been able to find anything online that is related to this issue. Could anybody help me out here? Thank you!
EDIT: Apologies as this is my first time asking a question. Thanks for taking a look!
CODE:
public class AccountControllerTest {
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
}
#After
public void tearDown() {
}
/**
* Test of register method, of class AccountController.
*/
#Test
public void testRegister() {
System.out.println("register");
String username = "";
String password = "";
String cfmPassword = "";
String email = "";
String name = "";
ArrayList<String> errorList = null;
AccountController instance = new AccountController();
instance.register(username, password, cfmPassword, email, name, errorList);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
Error Stacktrace:
Exception in thread "main" java.lang.UnsatisfiedLinkError:
junit.framework.TestResult.addListener(Ljunit/framework/TestListener;)V
at junit.framework.TestResult.addListener(Native Method) at
org.apache.tools.ant.taskdefs.optional.junit.IgnoredTestResult.addListener(IgnoredTestResult.java:49)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:357)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1179)
at
org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:1030)

JUnit : When do I declare a TemporaryFolder object?

I am trying to test a method that copies a source file to a dest file using JUnit's TemporaryFolder. I get a Java IOException when I try run this test however. Does it matter where I make the declaration for the folder? (My test class has several different tests in it). And if so, what is the proper way to do it? I ask because I currently have several unit tests above this code, then I try to set up the testing for the file copying. Maybe the #Rule-#Before-#Test block needs to be in its own class? Here is the snippet where I have coded the test:
...other tests...then:
#Rule
public static TemporaryFolder tmp = new TemporaryFolder();
private File f1, f2;
#Before
public void createTestData() throws IOException {
f1 = tmp.newFile("src.txt");
f2 = tmp.newFile("dest.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1));
out.write("This should generate some \n" +
"test data that will be used in \n" +
"the following method.");
out.close();
}
#Test
public void copyFileTest() {
out.println("file 1 length: " + f1.length());
try {
copyFile(f1, f2);
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
if (f1.length() != f2.length())
fail();
else if (!f1.equals(f2))
fail();
assertSame(f1, f2);
}
When I run this test class, all 11 of my tests now fail (which previously passed) and I get java.io.IOException: No such file or directory.
So looking at the JUnit Javadoc, I have found out that any declaration under #Rule must be public, and not static. So I took out the static and just have:
#Rule
public TemporaryFolder tmp = new TemporaryFolder();
I still do not know for sure if it matters where this declaration is made when you have other unit tests in your class that do not use the #Rule declaration, but this did allow me to run through my tests successfully.
If you really want to declare TemporaryFolder as static, you can use #ClassRule which is used to annotate static fields that contains Rule.
#ClassRule
public static TemporaryFolder tmp = new TemporaryFolder();
Reference: http://junit-team.github.io/junit/javadoc/4.10/org/junit/ClassRule.html

JUnit Rule TemporaryFolder

I'm creating a TemporaryFolder using the #Rule annotation in JUnit 4.7. I've tried to create a new folder that is a child of the temp folder using tempFolder.newFolder("someFolder") in the #Before (setup) method of my test. It seems as though the temporary folder gets initialized after the setup method runs, meaning I can't use the temporary folder in the setup method. Is this correct (and predictable) behavior?
This is a problem in Junit 4.7. If you upgrade a newer Junit (for example 4.8.1) all #Rule will have been run when you enter the #Before method:s. A related bug report is this: https://github.com/junit-team/junit4/issues/79
This works as well. EDIT if in the #Before method it looks like myfolder.create() needs called. And this is probably bad practice since the javadoc says not to call TemporaryFolder.create(). 2nd Edit Looks like you have to call the method to create the temp directories if you don't want them in the #Test methods. Also make sure you close any files you open in the temp directory or they won't be automatically deleted.
<imports excluded>
public class MyTest {
#Rule
public TemporaryFolder myfolder = new TemporaryFolder();
private File otherFolder;
private File normalFolder;
private File file;
public void createDirs() throws Exception {
File tempFolder = myfolder.newFolder("folder");
File normalFolder = new File(tempFolder, "normal");
normalFolder.mkdir();
File file = new File(normalFolder, "file.txt");
PrintWriter out = new PrintWriter(file);
out.println("hello world");
out.flush();
out.close();
}
#Test
public void testSomething() {
createDirs();
....
}
}

Categories

Resources