How to fix Saml assertion Exception (NoClassDefFoundError) - java

Hi guys i've created a saml assertion with opensaml-j and when i run the program an exception occurs and throws NoClassDefFoundError
i've loaded all the necessary jar files but still don't work
here's my code:
package memory;
import java.security.SecureRandom;
import org.joda.time.DateTime;
import org.opensaml.saml.common.SAMLVersion;
import org.opensaml.saml.saml1.core.AttributeStatement;
import org.opensaml.saml.saml1.core.AttributeValue;
import org.opensaml.saml.saml1.core.NameIdentifier;
import org.opensaml.saml.saml1.core.Subject;
import org.opensaml.saml.saml1.core.impl.EvidenceBuilder;
import org.opensaml.saml.saml1.core.impl.NameIdentifierBuilder;
import org.opensaml.saml.saml1.core.impl.SubjectBuilder;
import org.opensaml.saml.saml2.core.Action;
import org.opensaml.saml.saml2.core.Assertion;
import org.opensaml.saml.saml2.core.Attribute;
import org.opensaml.saml.saml2.core.AuthzDecisionStatement;
import org.opensaml.saml.saml2.core.Conditions;
import org.opensaml.saml.saml2.core.DecisionTypeEnumeration;
import org.opensaml.saml.saml2.core.Evidence;
import org.opensaml.saml.saml2.core.Issuer;
import org.opensaml.saml.saml2.core.impl.ActionBuilder;
import org.opensaml.saml.saml2.core.impl.AssertionBuilder;
import org.opensaml.saml.saml2.core.impl.AttributeBuilder;
import org.opensaml.saml.saml2.core.impl.AttributeStatementBuilder;
import org.opensaml.saml.saml2.core.impl.AuthzDecisionStatementBuilder;
import org.opensaml.saml.saml2.core.impl.ConditionsBuilder;
import org.opensaml.saml.saml2.core.impl.IssuerBuilder;
public class CreateSamlAssertion {
#SuppressWarnings("deprecation")
public static Assertion createAssertion(){
Assertion assertion=(Assertion)new AssertionBuilder().buildObject();
assertion.setID(idGenerator());
assertion.setVersion(SAMLVersion.VERSION_20);
assertion.setIssueInstant(new DateTime());
Issuer issuer=(Issuer)new IssuerBuilder().buildObject();
issuer.setNameQualifier("bob");
assertion.setIssuer(issuer);
Subject subject=(Subject)new SubjectBuilder().buildObject();
NameIdentifier nameId=(NameIdentifier)new NameIdentifierBuilder().buildObject();
nameId.setFormat(NameIdentifier.EMAIL);
nameId.setNameIdentifier("alice");
subject.setNameIdentifier(nameId);
Conditions conditions=(Conditions)new ConditionsBuilder().buildObject();
conditions.setNotBefore(new DateTime());
conditions.setNotOnOrAfter(new DateTime().plusMinutes(20));
assertion.setConditions(conditions);
AuthzDecisionStatement authDecisionStatement=getAuthzDecisionStatement();
assertion.getAuthzDecisionStatements().add(authDecisionStatement);
return assertion;
}
private static AuthzDecisionStatement getAuthzDecisionStatement(){
AuthzDecisionStatement aDStatement=(AuthzDecisionStatement)new AuthzDecisionStatementBuilder().buildObject();
DecisionTypeEnumeration decision = DecisionTypeEnumeration.PERMIT;
aDStatement.setDecision(decision);
aDStatement.setResource("http://www.hb.com/Resources/Resource A1");
Action actions=getAction();
actions.setNamespace("http://www.hb.com/Resources/");
aDStatement.getActions().add(actions);
Evidence evidence=getEvidence();
aDStatement.setEvidence(evidence);
return aDStatement;
}
private static Evidence getEvidence(){
Evidence evidence=(Evidence)new EvidenceBuilder().buildObject();
Assertion assertion=(Assertion)new AssertionBuilder().buildObject();
AttributeStatement aStatement=(AttributeStatement) new AttributeStatementBuilder().buildObject();
Attribute attribute1=(Attribute)new AttributeBuilder().buildObject();
attribute1.setName("IssuerCapabilityID");
AttributeValue aValue1=(AttributeValue) AttributeValue.DEFAULT_ELEMENT_NAME;
attribute1.getAttributeValues().add(aValue1);
Attribute attribute2=(Attribute)new AttributeBuilder().buildObject();
attribute2.setName("IssuerCapabilityID");
AttributeValue aValue2=(AttributeValue) AttributeValue.DEFAULT_ELEMENT_NAME;
attribute1.getAttributeValues().add(aValue2);
aStatement.getAttributes().add((org.opensaml.saml.saml1.core.Attribute) attribute1);
aStatement.getAttributes().add((org.opensaml.saml.saml1.core.Attribute) attribute2);
assertion.getAttributeStatements().add((org.opensaml.saml.saml2.core.AttributeStatement) aStatement);
evidence.getAssertions().add(assertion);
return evidence;
}
private static Action getAction(){
Action action=(Action)new ActionBuilder().buildObject();
action.setAction("Read");
action.setAction("Write");
return action;
}
private static String idGenerator(){
SecureRandom random=new SecureRandom();
return String.valueOf(random.nextInt());
}
}
and here's the main class:
package memory;
import org.opensaml.saml.saml2.core.Assertion;
public class SamlTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Assertion assertion=CreateSamlAssertion.createAssertion();
System.out.println(assertion);
}
}
the stack trace
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.opensaml.core.xml.AbstractXMLObject.<init>(AbstractXMLObject.java:47)
at org.opensaml.xmlsec.signature.AbstractSignableXMLObject.<init>(AbstractSignableXMLObject.java:47)
at org.opensaml.saml.common.AbstractSignableSAMLObject.<init>(AbstractSignableSAMLObject.java:44)
at org.opensaml.saml.saml2.core.impl.AssertionImpl.<init>(AssertionImpl.java:83)
at org.opensaml.saml.saml2.core.impl.AssertionBuilder.buildObject(AssertionBuilder.java:45)
at org.opensaml.saml.saml2.core.impl.AssertionBuilder.buildObject(AssertionBuilder.java:40)
at memory.CreateSamlAssertion.createAssertion(CreateSamlAssertion.java:34)
at memory.SamlTest.main(SamlTest.java:9)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 8 more
and thanks in advance

Related

Java - MalformedURLException when inputting String from another class, but not when pasting that same String in

When instantiating a new URL, the first block of code below, from the class DrawImage works.
However, when I input the same String ("https://www.purchased.com/hubfs/template/favicon.png") from another class, RandomImage, the following error comes up:
I tried first with manually inputting the String.
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DrawImage {
public static void main(String[] args) throws Exception {
String link = "https://www.purchased.com/hubfs/template/favicon.png";
System.setProperty("http.agent", "Chrome");
URL url = new URL(link);
Image image = ImageIO.read(url.openStream());
}
}
-> works as expected
Then, I changed to providing a RandomImage (this is the one that yields the error message!)
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DrawImage {
public static void main(String[] args) throws Exception {
RandomImage img = new RandomImage();
String link = img.link;
System.setProperty("http.agent", "Chrome");
URL url = new URL(link);
Image image = ImageIO.read(url.openStream());
}
}
Following class provides the random image:
import java.net.*;
import java.io.*
public class RandomImage {
public static String link;
public RandomImage() throws Exception {
this.link = generateUsableImageLink();
}
But when running this second approach, I am getting following error:
java.net.MalformedURLException: no protocol: "https://www.purchased.com/hubfs/template/favicon.png"
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at DrawImage.main(DrawImage.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267).
I tried (as you see in code above) making RandomImage an object, but the error feed tells me the error is occurring when I create an instance of URL with input from RandomImage.
If I were to guess, the issue is caused by some interaction between imported packages or thrown errors in RandomImage. Character by character, the String I manually inputted and the String generated by RandomImage are identical. How would I go about addressing this?
Method generateUsableImageLink generates string with quotes.
Change this method so that it does not put quotes on the string.

simple JXLS / Apache POI example fails

I have no idea way I get this error. The code is from JXLS own example and the Jars are downloaded from there page.
Error code:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.jxls.util.TransformerFactory.loadPoiTransformer(TransformerFactory.java:85)
at org.jxls.util.TransformerFactory.getTransformerClass(TransformerFactory.java:69)
at org.jxls.util.TransformerFactory.createTransformer(TransformerFactory.java:27)
at org.jxls.util.JxlsHelper.createTransformer(JxlsHelper.java:250)
at org.jxls.util.JxlsHelper.processTemplate(JxlsHelper.java:108)
at test_excel.ObjectCollectionDemo.main(ObjectCollectionDemo.java:32)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 8 more
Referenced Libraries:
/slf4j-1.7.25/slf4j-api-1.7.25.jar
/slf4j-1.7.25/slf4j-jdk14-1.7.25.jar
/jxls-2.4.1 2/dist/jxls-reader-2.0.3.jar
/jxls-2.4.1 2/dist/jxls-poi-1.0.13.jar
/xls-2.4.1 2/dist/jxls-jexcel-1.0.6.jar
/jxls-2.4.1 2/dist/jxls-2.4.1.jar
Main code:
package test_excel;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ObjectCollectionDemo {
private static Logger logger = LoggerFactory.getLogger(ObjectCollectionDemo.class);
public static void main(String[] args) throws ParseException, IOException {
logger.info("Running Object Collection demo");
List<Employee> employees = generateSampleEmployeeData();
try(InputStream is = ObjectCollectionDemo.class.getResourceAsStream("object_collection_template.xls")) {
try (OutputStream os = new FileOutputStream("object_collection_output.xls")) {
Context context = new Context();
context.putVar("employees", employees);
logger.info("OK so far...");
JxlsHelper.getInstance().processTemplate(is, os, context);
}
}
}
public static List<Employee> generateSampleEmployeeData() throws ParseException {
List<Employee> employees = new ArrayList<Employee>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd", Locale.US);
employees.add( new Employee("Elsa", dateFormat.parse("1970-Jul-10"), 1500, 0.15) );
employees.add( new Employee("Oleg", dateFormat.parse("1973-Apr-30"), 2300, 0.25) );
employees.add( new Employee("Neil", dateFormat.parse("1975-Oct-05"), 2500, 0.00) );
employees.add( new Employee("Maria", dateFormat.parse("1978-Jan-07"), 1700, 0.15) );
employees.add( new Employee("John", dateFormat.parse("1969-May-30"), 2800, 0.20) );
return employees;
}
}
Looks like you need poi-3.XX.jar in your class path - see here.

i get ClassNotFoundException when i try to read from excel file

When i try to read from excel file using apace poi i get the ClassNotFoundException followed by other errors and i have imported all the necessary jar files in the reference library
by the way i'm still new to coding
heres the code :
import java.io.*;
import java.io.File;
import java.io.FilterInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.*;
import org.apache.poi.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream F = new FileInputStream("Carbcounting.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(F);
XSSFSheet sheet = wb.getSheetAt(0);
FormulaEvaluator formulaEva = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet){
for(Cell cell : row){
System.out.print(cell.getStringCellValue());
}
}
System.out.println();
}
}
and heres all the errors i'm getting when i try to run it :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap
at project.Test.main(Test.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections4.ListValuedMap
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
You need to Add commons-collections4-x.x.jar file in your build path and try it again. It should work.
Get it from here: https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0
Also, just adding up:
You are getting this error(NoClassDefFoundError) majorly for two reasons:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.

Test passed in IDE but failed in TeamCity

I have a class that i had to test:
package com.mycompany.openapi.cms.core.support.liquibase;
import liquibase.change.custom.CustomTaskChange;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.CustomChangeException;
import liquibase.exception.SetupException;
import liquibase.exception.ValidationErrors;
import liquibase.resource.ResourceAccessor;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Statement;
import java.util.Set;
public class ApplySqlFileIfExistsChange implements CustomTaskChange {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
private String file;
private ResourceAccessor resourceAccessor;
#Override
public void execute(Database database) throws CustomChangeException {
JdbcConnection databaseConnection = (JdbcConnection) database.getConnection();
try {
Set<InputStream> files = resourceAccessor.getResourcesAsStream(file);
if(files != null){
for (InputStream inputStream : files) {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream));
String str;
String sql;
StringBuilder sqlBuilder = new StringBuilder("");
while ((str = in.readLine()) != null) {
sqlBuilder.append(str).append(" ");
}
in.close();
sql = sqlBuilder.toString().trim();
if(StringUtils.isEmpty(sql)){
return;
}
Statement statement = databaseConnection.createStatement();
statement.execute(sql);
statement.close();
}
}
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
throw new CustomChangeException(e);
}
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
#Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
this.resourceAccessor = resourceAccessor;
}
}
I had written the test:
package com.mycompany.openapi.cms.core.support.liquibase;
import com.google.common.collect.Sets;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.resource.ResourceAccessor;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Statement;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest({LoggerFactory.class})
public class TestApplySqlFileIfExistsChange {
#InjectMocks
ApplySqlFileIfExistsChange applySqlFileIfExistsChange;
#Mock
private ResourceAccessor resourceAccessor;
#Mock
private JdbcConnection jdbcConnection;
#Mock
private Database database;
#Mock
Statement statement;
#BeforeClass
public static void setUpClass() {
mockStatic(LoggerFactory.class);
when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(mock(Logger.class));
}
#Before
public void setUp() throws Exception {
when(database.getConnection()).thenReturn(jdbcConnection);
InputStream inp1, inp2;
inp1 = new ByteArrayInputStream("FirstTestQuery".getBytes(StandardCharsets.UTF_8));
inp2 = new ByteArrayInputStream("SecondTestQuery".getBytes(StandardCharsets.UTF_8));
when(resourceAccessor.getResourcesAsStream(anyString())).thenReturn(Sets.newHashSet(inp1, inp2));
when(jdbcConnection.createStatement()).thenReturn(statement);
}
#Test
public void execute() throws Exception {
applySqlFileIfExistsChange.execute(database);
verify(statement).execute("FirstTestQuery");
verify(statement).execute("SecondTestQuery");
}
}
Problem is that test above passed in my IDE, but when i make push in repository TeamCity build failed on my test. I can't undestand why, because code are same in both places. Here is stack trace in TeamCity:
java.lang.IllegalStateException: Failed to transform class with name org.slf4j.LoggerFactory. Reason: java.io.IOException: invalid constant type: 15
at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:267)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:180)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:439)
at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:420)
at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724)
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getAnnotation(Class.java:3415)
at org.junit.internal.MethodSorter.getDeclaredMethods(MethodSorter.java:52)
at org.junit.internal.runners.TestClass.getAnnotatedMethods(TestClass.java:45)
at org.junit.internal.runners.MethodValidator.validateTestMethods(MethodValidator.java:71)
at org.junit.internal.runners.MethodValidator.validateStaticMethods(MethodValidator.j
I apologize for such a number of code in my question.
You probably have conflicting Powermock/Mockito versions.
Check your local maven repo for the versions, and get rid of the older ones
in your pom and/or update the other dependency which included it.
Check in the root of the project with:
mvn dependency:tree -Dverbose -Dincludes=NAME_OF_DEPENDENCY
You have a conflict of dependent libraries in the TeamCity repo vs your local repo.
Confirm the TC build is using the exact same version of Powermock that your local is using.
There may be an older version being transitively included.
mvn dependency:tree -Dverbose
This will list all the resolvable dependencies. See if there are different versions of Powermock. You can then stop them being possible pulled in by using the exclude/exclusions tag in the pom.xml.

Mocking file operations in a unit test using junit and PowerMockito doesn't work

I'm trying to write unit test for a static method which contains file operations. I'm using junit and PowerMockito. The method to be test is converting a csv file to bean list. Since this is unit test I mock a method call which is inside of our method. But the following error is occuring,
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods cannot be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.mypackage..unittest.UTCSVBeanUtil.convert_convertingCsvToBean(UTCSVBeanUtil.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
My class is,
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import au.com.bytecode.opencsv.bean.ColumnPositionMappingStrategy;
import au.com.bytecode.opencsv.bean.CsvToBean;
public class CSVBeanUtil {
public static <T> List<T> fileToBean(final String filename, final char delimiter, final Class<T> beanClass,
final String[] columns) throws FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
return bufferReaderToBean(reader, delimiter, beanClass, columns);
} finally {
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
// ignore
}
}
}
}
public static <T> List<T> stringToBean() {
return null;
}
public static <T> List<T> bufferReaderToBean(BufferedReader reader, final char delimiter, final Class<T> beanClass,
final String[] columns) {
CSVReader csvreader = null;
final CsvToBean<T> csv = new CsvToBean<T>();
csvreader = new CSVReader(reader, delimiter);
ColumnPositionMappingStrategy<T> strategy = new ColumnPositionMappingStrategy<T>();
strategy.setType(beanClass);
strategy.setColumnMapping(columns);
return csv.parse(strategy, csvreader);
}
public static boolean writeToCsv(List<String[]> beanList, Path absPath) throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter(absPath.toAbsolutePath().toString()),
CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
writer.writeAll(beanList);
writer.close();
return false;
}
}
And my test class is,
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import com.mypackage..config.AppConfig;
import com.mypackage..entity.MyFile;
import com.mypackage..service.MyFileValidation;
import com.mypackage..utility.CSVBeanUtil;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
#WebAppConfiguration
#ContextConfiguration(classes = { AppConfig.class })
#PrepareForTest(CSVBeanUtil.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class UTCSVBeanUtil {
List<MyFile> dataList = new ArrayList<MyFile>();
List<MyFile> expectedList=new ArrayList<MyFile>();
#Before
public void beforeClass() {
expectedList = getdataList();
}
#Test
public void convert_convertingCsvToBean()
throws IOException{
PowerMockito.mockStatic(CSVBeanUtil.class);
// BufferedReader bufferedReader = Mockito.mock(BufferedReader.class); // while using this the test execution doesn't terminate
BufferedReader bufferedReader= new BufferedReader(new StringReader("201030"));
// File file = Mockito.mock(File.class);
Mockito.when(CSVBeanUtil.bufferReaderToBean(bufferedReader, ',', MyFile.class, MyFile.columns))
.thenReturn(expectedList);
dataList.addAll(CSVBeanUtil.fileToBean( null, ',', MyFile.class, MyFile.columns));
assertEquals(expectedList,dataList);
}
private List<MyFile> getdataList() {
List<MyFile> expectedList=new ArrayList<MyFile>();
MyFile gv=new MyFile();
gv.setTRADENUM("201030");
expectedList.add(gv);
return expectedList;
}
}
I'm trying to solve this problem. Please help me... Thank You
PowerMock provides it's own runner, specified with the #RunWith annotation
#RunWith( PowerMockRunner.class)
If you want to use SpringJUnit4ClassRunner.class
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
Using another JUnit Runner with PowerMock

Categories