So I have these two methods in a class:
public String getConsumerKey() throws FileNotFoundException, IOException
{
String consumerKey;
consumerKey = getPropertyValueOrNull(getConfigPath(CONSUMERVALUESCONFIGNAME),"consumer_key");
return consumerKey;
}
private String getPropertyValueOrNull(String path, String key) throws FileNotFoundException, IOException
{
Properties prop = new Properties();
String value = null;
// load a properties file
prop.load(new FileInputStream(path));
value = prop.getProperty(key);
if ( value == null || value.isEmpty())
{
value = null;
}
return value;
}
And I call getCosumerKey() from the main method like this:
public static void main(String[] args)
{
try {
MyClass.getInstance().getConsumerKey();
} catch (IOException e) {
e.printStackTrace();
}
}
When I run this code, there is no problem except that I am getting a FileNotFoundExcpetion. When I tried to add a catch block to handle the FileNotFoundException, I got an error saying that the exception is already handled from the IOException catch block.
Isn't the compiler supposed to prevent me from running the code and why does not compiler let me handle the exception?
Related
here is the code for which I want to write a test case for catch block
public class X {
protected String getInputString(final String inputPath) {
try {
return Resources.asCharSource(Resources.getResource(inputPath), UTF_8).read();
} catch (final IOException e) {
log.error("Error loading partner aliases from local config", e);
throw new UncheckedIOException(e);
}
}
}
have tried mocking the staic method asCharSource as bellow:
#Test
public void Failed() throws Exception{
URL url = Resources.getResource("resources/linearPartners.json");
CharSource s;
try{
s = new CharSource() {
#Override
public Reader openStream() throws IOException {
throw new IOException("Expected as a test");
}
#Override
public String read() throws IOException {
throw new IOException("Expected as a test");
}
};
try (MockedStatic<Resources> resources = Mockito.mockStatic(Resources.class)) {
resources.when(() -> Resources.asCharSource(url, UTF_8))
.thenReturn(s);
Assertions.assertThrows(UncheckedIOException.class, () -> staticConfigPartnerAliasesPersistenceFacade.getInputString("resources/file.json"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
bellow is the error
org.opentest4j.AssertionFailedError: Unexpected exception type thrown ==> expected: <java.io.UncheckedIOException> but was: <java.lang.NullPointerException>
[java] org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:65)
[java] org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:37)
[java] org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:3082)
I did not understand, where is the NullPointerException is coming from. Please guide me on this
I need to write a test to verify that when an IOException is thrown by the private method_C, Method_B returns True.
But
public final class A{
public static Boolean Method_B(){
try{
//call a private method C which throws IOException
Method_C
}
catch(final IOException e) {
return Boolean.True
}
}
private static Method_C() throws IOException {
return something;
}
What I tried:
#Test
public void testSomeExceptionOccured() throws IOException {
A Amock = mock(A.class);
doThrow(IOException.class).when(Amock.Method_C(any(),any(),any(),any()));
Boolean x = A.Method_B(some_inputs);
Assert.assertEquals(Boolean.TRUE, x);
}
I am getting compilation errors :
1.Cannot mock a final class
2. Method_C has private access in A
Any suggestions on how this can be rectified?
you are required to use finally in try catch
import java.io.*;
public class Test {
public static Boolean Method_B() {
try {
System.out.println("Main working going..");
File file = new File("./nofile.txt");
FileInputStream fis = new FileInputStream(file);
} catch (IOException e) {
// Exceptiona handling
System.out.println("No file found ");
} catch (Exception e) {
// Exceptiona handling
System.out.println(e);
} finally {
return true;
}
}
public static void main(String args[]) {
if (Test.Method_B()) {
System.out.println("Show true ans");
} else {
System.out.println("Sorry error occure");
}
}
}
i am trying to test a private method inside an ActionListener. The method should throw an exception if an invalid url is passed:
Heres the code of my test:
#Rule
public ExpectedException expectedException = ExpectedException.none();
Map<JLabel, JTextField> inputs;
ActionListener listener;
AddStationWindow window;
ArrayList<Station> stationsToDelete;
#Before
public void setUp() throws IllegalAccessException, NoSuchFieldException,
InstantiationException, SQLException, ClassNotFoundException {
inputs = new HashMap<JLabel, JTextField>();
window = new AddStationWindow();
stationsToDelete = new ArrayList<>();
InitializeH2Database.initialiteDatabase();
}
#Test
public void saveStation() throws NoSuchFieldException,
IllegalAccessException, MalformedURLException, NoSuchMethodException,
InvocationTargetException {
Field f = window.getClass().getDeclaredField("inputElements");
f.setAccessible(true);
LinkedHashMap<JLabel, JTextField> inputs = (LinkedHashMap<JLabel,
JTextField>) f.get(window);
Field f2 = window.getClass().getDeclaredField("save");
f2.setAccessible(true);
JButton saveButton = (JButton) f2.get(window);
inputs.get(window.getInputLabels().get(0)).setText("Testsender");
inputs.get((window.getInputLabels().get(1))).setText("asdasdsa");
ActionListener listener = saveButton.getActionListeners()[0];
Method m = listener.getClass().getDeclaredMethod("saveStation");
m.setAccessible(true);
m.invoke(listener);
expectedException.expect(MalformedURLException.class);
}
#After
public void tearDown() {
stationsToDelete.forEach(s ->
H2DatabaseConnector.getInstance().deleteStation(s));
}
This is the tested method inside the ActionListener:
private boolean saveStation() {
List<JLabel> keys = new ArrayList<>();
for (Map.Entry<JLabel, JTextField> inputElement : inputElements.entrySet()) {
keys.add(inputElement.getKey());
}
String stationName = inputElements.get(keys.get(0)).getText();
String urlString = inputElements.get(keys.get(1)).getText();
URL stationURL = null;
try {
stationURL = new URL(urlString);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(window, "Invalid URL!", "URL
not valid", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return false;
}
Station s = new Station(stationName, stationURL);
if (checkStation(s)) {
return WebradioPlayer.addStation(s);
}
return false;
}
If i run the test, i can see that the stack tarce shows the malformed url exception with message no protocol: 'asdasdsa', but the test fails.
Can someone explain me why? JUnit version is 4.
You have to set the expected exception before you call the code that actually does throw the exception.
Instead of
#Test
public void saveStation() throws ... {
// code here
expectedException.expect(MalformedURLException.class);
}
you should write the test method as
#Test
public void saveStation() throws ... {
expectedException.expect(MalformedURLException.class);
// code here
}
Additionally, you have to change your method saveStation to not suppress the exception if you actually want to have it thrown. See #Leviand's answer for more details.
Your test is failing because you are expecting an exception to be thrown (you said invalid url exception), but you are wrapping that exception into a try catch, then you are printing the stacktrace.
try {
stationURL = new URL(urlString);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(window, "Invalid URL!", "URL
not valid", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return false;
}
you have to add the trown declaration in your catch, or not catch it at all, ie:
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(window, "Invalid URL!", "URL
not valid", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
throw new MalformedURLException(e);
}
and add the throw info to your method
private boolean saveStation() throws MalformedURLException{
I have some problems throwing my own exception. Here is the code:
class MyException extends Exception {
private String message;
public MyException(String message) {
this.message = message;
}
#Override
public String toString() {
return "Something went wrong: " + message;
}
}
code where MyException is thrown:
static void expand(String input, String output) throws MyException {
try {
Scanner sc = new Scanner(new File(input));
//do something with scanner
} catch (FileNotFoundException e) {
throw new MyException("File not found!");
}
}
and the main method:
public class Encode {
public static void main(String[] args) throws MyException {
expand("ifiififi.txt", "fjifjif.txt");
System.out.println("ok");
}
the exception is thrown normally, the message is printed normally, but the program is terminated and the "ok" message is not printed out.
Exception in thread "main" Something went wrong: File not found!
at vaje3.Encode.expand(Encode.java:59)
at vaje3.Encode.main(Encode.java:10)
Java Result: 1
You are making life hard on yourself trying to cast a new exception. You dont need to do that, just pass the original up. This is better practice since the FileNotFoundException is a standard error so it is a convention shared by most programmers.
public class Encode {
static void expand(String input, String output)
throws FileNotFoundException
{
Scanner sc = new Scanner(new File(input));//no try catch here or new exception
//just let the original be passed up
//via the throw directive
//Do more here.
}
public static void main(String[] args) {
try{
expand("ifiififi.txt", "fjifjif.txt");
} catch ( FileNotFoundException fnfe ){
System.err.println("Warning File not found");
fnfe.printStackTrace();
}
}
}
main method:
public static void main(String[] args) throws Exception
{
if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS)
{
System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR");
}
String configXML = args[0];
String packageXML = args[1];
String xfr = args[2];
AutoConfigCompiler compiler = new AutoConfigCompiler();
compiler.setConfigDocument(loadDocument(configXML));
compiler.setPackageInfoDoc(loadDocument(packageXML));
// compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml"));
compiler.compileModel(xfr);
}
private static Document loadDocument(String fileName) throws Exception
{
TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName());
InputSource source = new InputSource(new FileInputStream(fileName));
parser.parse(source);
return parser.getDocument();
}
testcase:
#Test
public void testCompileModel() throws Exception
{
// construct parameters
URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml");
URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml");
File tmpFile = new File("Ford_2008_Mustang_tmp.xfr");
if(!tmpFile.exists()) {
tmpFile.createNewFile();
}
String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()};
try {
// test main method
XFRCompiler.main(args);
} catch (Exception e) {
assertTrue(true);
}
try {
// test args length is less than 3
XFRCompiler.main(new String[]{"",""});
} catch (Exception e) {
//ignore
}
tmpFile.delete();
}
Coverage outputs displayed as the lines from String configXML = args[0]; in main method
are not covered.
assertTrue(true); is a pointless no-op
Remove the try/catch around the call to XFRCompiler.main(args);, since all it does is swallow excpetions and make debugging harder; most likely you will then see an exception that tells you where the problem is.
There should be a call to fail() after the call to XFRCompiler.main(new String[]{"",""}); since you expect it to throw an exception
Put the two calls in separate test methods.
I'm worried about all those assertTrue(true). If there can't be an exception, then the assert is not necessary. If there is an unexpected exception, then this code will swallow it and you will get the behavior you see right now.
Then, if you expect an exception, you should code like this:
try {
... code that will throw an exception ...
fail("No exception was thrown");
} catch (SpecficTypeOfException e) {
assertEquals("message", e.getMessage());
}
That way, wrong types of exception and the exception message will be checked.
PS: Don't post questions with "urgent". We already help as fast as we can.