Rest assured + properties baseURI cannot be null class not loaded - java

I have ConfigProperties.class
public class ConfigProperties {
#BeforeTest
public void TestDataSetup() throws FileNotFoundException {
File src = new File("src\\main\\resources\\config.properties");
FileInputStream fis = new FileInputStream(src);
ConfigProperties properties = new ConfigProperties();
properties.load(fis);
}
public void load(FileInputStream fis) {
}
}
below test method
public class Paragraphs extends ConfigProperties {
Properties prop = new Properties();
public void createParagraph() {
RestAssured.baseURI = prop.getProperty("paragraphsURL");
here is config.properties
paragraphsURL=http://192.168.0.139:8880/paragraphs
After running my test I received error
java.lang.IllegalArgumentException: baseURI cannot be null
After debugging I have
RestAssured.baseURI = Class not loaded : io.restassured.RestAssured

Related

Mockito UnfinishedVerificationException

The problem is the following. I have several reports that I want to mock and test with Mockito. Each report gives the same UnfinishedVerificationException and nothing that I tried so far worked in order to fix the issue. Example of one of the reports with all parents is below.
I changed any to anyString.
Change ReportSaver from interface to abstract class
Add validateMockitoUsage to nail the right test
Looked into similar Mockito-related cases on StackOverflow
Test:
public class ReportProcessorTest {
private ReportProcessor reportProcessor;
private ByteArrayOutputStream mockOutputStream = (new ReportProcessorMock()).mock();
#SuppressWarnings("serial")
private final static Map<String, Object> epxectedMaps = new HashMap<String, Object>();
#Before
public void setUp() throws IOException {
reportProcessor = mock(ReportProcessor.class);
ReflectionTestUtils.setField(reportProcessor, "systemOffset", "Europe/Berlin");
ReflectionTestUtils.setField(reportProcessor, "redisKeyDelimiter", "#");
Mockito.doNothing().when(reportProcessor).saveReportToDestination(Mockito.any(), Mockito.anyString());
Mockito.doCallRealMethod().when(reportProcessor).process(Mockito.any());
}
#Test
public void calculateSales() throws IOException {
Map<String, Object> processedReport = reportProcessor.process(mockOutputStream);
verify(reportProcessor, times(1)); // The line that cause troubles
assertThat(Maps.difference(processedReport, epxectedMaps).areEqual(), Matchers.is(true));
}
#After
public void validate() {
Mockito.validateMockitoUsage();
}
}
Class under test:
#Component
public class ReportProcessor extends ReportSaver {
#Value("${system.offset}")
private String systemOffset;
#Value("${report.relativePath}")
private String destinationPathToSave;
#Value("${redis.delimiter}")
private String redisKeyDelimiter;
public Map<String, Object> process(ByteArrayOutputStream outputStream) throws IOException {
saveReportToDestination(outputStream, destinationPathToSave);
Map<String, Object> report = new HashMap<>();
try (InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
InputStreamReader reader = new InputStreamReader(inputStream)) {
CSVReaderHeaderAware csvReader = new CSVReaderFormatter(outputStream).headerAware(reader);
Map<String, String> data;
while ((data = csvReader.readMap()) != null) {
String data = data.get("data").toUpperCase();
Long quantity = NumberUtils.toLong(data.get("quantity"));
report.put(data, quantity);
}
}
return report;
}
}
Parent class:
public abstract class ReportSaver {
public void saveReportToDestination(ByteArrayOutputStream outputStream, String destinationPathToSave) throws IOException {
File destinationFile = new File(destinationPathToSave);
destinationFile.getParentFile().mkdirs();
destinationFile.delete();
destinationFile.createNewFile();
OutputStream fileOutput = new FileOutputStream(destinationFile);
outputStream.writeTo(fileOutput);
}
}
Mock:
public class ReportProcessorMock implements GeneralReportProcessorMock {
private static final String report = ""; // There can be some data in here
#Override
public ByteArrayOutputStream mock() {
byte[] reportBytes = report.getBytes();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(reportBytes.length);
outputStream.write(reportBytes, 0, reportBytes.length);
return outputStream;
}
}
When you verify, you verify a particular public method of the mock:
verify(reportProcessor, times(1)).process(mockOutputStream);
or use a wildcard if appropriate:
verify(reportProcessor, times(1)).process(any(ByteArrayOutputStream.class));

How can i test Solr SearchComponent - JUnit Tests

I need to write a unit test for solr SearchComponent (SearchComponent.process ()).
How could I do that? Can I use SolrTestCaseJ4 or another way?
I am currently using SolrTestCaseJ4...
I am currently using SolrTestCaseJ4...
public class SearchComponentTest extends SolrTestCaseJ4 {
#BeforeClass
public static void beforeClass() throws Exception {
initCore("collection1/conf/solrconfig.xml", "collection1/conf/schema.xml", "src/test/resources/");
}
#Test
public void testPrepare() throws IOException {
MySearchComponent component = new MySearchComponent();
List<SearchComponent> components = new ArrayList<>();
components.add(component);
SolrQueryRequest req;
ResponseBuilder rb;
req = req("q", "*:*");
rb = new ResponseBuilder(req, new SolrQueryResponse(), components);
component.process(rb);
}
}
and my SearchComponent:
public class MySearchComponent extends SearchComponent {
public void process(ResponseBuilder rb) throws IOException {
....
SolrQueryRequest req = rb.req;
SolrQueryResponse rsp = rb.rsp;
SolrParams params = rb.req.getParams();
SchemaField keyField = rb.req.getCore().getLatestSchema().getUniqueKeyField();
String core = rb.req.getCore().getName();
SolrIndexSearcher searcher = req.getSearcher();
QueryCommand cmd = rb.createQueryCommand();
QueryResult result = new QueryResult();
searcher.search(result, cmd);
rb.setResult(result);
BasicResultContext ctx = new BasicResultContext(rb, rb.getResults().docList);
rsp.add("response", ctx);
...
}
...
}
But i have NullPointerException on this line:
QueryCommand cmd = rb.createQueryCommand();
Thank you for your help!

How to mock a method that returns a file

In my unit testing, I want to mock a method which returns a file in java. How do I mock a method that returns a file in java? The code looks something along the lines of
private File baseDirectory;
private String fileName;
private File file;
public File getFile(String userName, String hostName)
throws VerifyException, IOException {
hostName = "/" + hostName;
userName = "/" + userName;
baseDirectory = new File(hostName, userName);
if (!baseDirectory.exists()) {
baseDirectory.mkdirs();
}
fileName = new SimpleDateFormat("yyyyMMddhhmmssSSS'.txt'").format(new Date());
file = new File(baseDirectory, fileName);
if (!file.exists()) {
file.createNewFile();
}
return file;
}
Since you mentioned Mockito - here's a quick test I came up with. Done using Mockito Annotations.
#Mock
FileFetcher fileFetcher;
#InjectMocks
ClassUnderTest classUnderTest;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testGetFile() throws VerifyException, IOException {
//set expectations
Mockito.when(fileFetcher.getFile(Mockito.anyString(), Mockito.anyString())).thenReturn(getTestFile());
//call
classUnderTest.getFileTest();
//verify
Mockito.verify(fileFetcher, Mockito.times(1));
}
private File getTestFile() {
return null;
}

Dynamic location for PropertySourcesPlaceholderConfigurer

i have annotation-based bean configuration for placeholder.
With the help of this placeholder, i can use properties values i want very easily.
#Bean
public static PropertySourcesPlaceholderConfigurer initPlaceholder() {
PropertySourcesPlaceholderConfigurer placeholder = new PropertySourcesPlaceholderConfigurer();
placeholder.setLocation(new ClassPathResource("some.properties"));
placeholder.setIgnoreUnresolvablePlaceholders(true);
return placeholder;
}
How i can set up this placeholder with ${some.properties} dynamic values?
placeholder.setLocation(new ClassPathResource(ANY_PROPERTIES));
I can not use initPlaceholder(String property)...
What I have done about this was create my own PropertyPlaceHolder (to get an external property file)
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
public static final String ANY_PROPERTY = "ANY_PROPERTY";
private static final Log LOG = LogFactory.getLog(MyPropertyPlaceholderConfigurer.class);
#Override
protected void loadProperties(Properties props) throws IOException {
String anyProperty = System.getProperty(ANY_PROPERTY);
if (StringUtils.isEmpty(anyProperty)) {
LOG.info("Using default configuration");
super.loadProperties(props);
} else {
LOG.info("Setting HDFS LOCATION PATH TO : " + anyProperty);
try {
Path pt = new Path(anyProperty);
Configuration conf = new Configuration();
conf.set(FileSystem.FS_DEFAULT_NAME_KEY, anyProperty);
FileSystem fs = FileSystem.get(conf);
FSDataInputStream fileOpen = fs.open(pt);
BufferedReader br = new BufferedReader(new InputStreamReader(fileOpen));
props.load(br);
} catch (Exception e) {
LOG.error(e);
}
}
}

loading the properties file

I wanted to read some properties file.
For that I created a small program which reads, writes and also updates this properties file.
Now some people are saying the properties file should be read only once, that means when the class is loaded it should read once, not multiple times for each key.
So I have to read the properties file inside a static block.
Now my doubt if I make any new entry to the properties file, will it be loaded the new entry ?
Please suggest me which is the correct way to design the loading of properties file.
public class Parser {
private String path;
private static Properties prop = new Properties();
public Parser(String path) throws IOException{
this.path = path;
load();
}
public Model readPropertiesFile(){
Model model = new Model();
model.setName(prop.getProperty("name"));
return model ;
}
public void createOrUpdatePropertiesFile(Model model){
prop.setProperty("name", model.getName());
}
public void setPath(String path){
this.path = path;
}
public String getPath(){
return path ;
}
public void load() throws IOException{
File file = new File(path);
if(!file.exists()){
file.createNewFile();
System.out.println("File created..");
}
prop.load(new FileInputStream(file));
}
You can try this ways;
Load properties file from classpath
public static Properties load(String propsName) throws Exception {
Properties props = new Properties();
URL url = ClassLoader.getSystemResource(propsName);
props.load(url.openStream());
return props;
}
Load a properties file
public static Properties load(File propsFile) throws IOException {
Properties props = new Properties();
FileInputStream fis = new FileInputStream(propsFile);
props.load(fis);
fis.close();
return props;
}

Categories