Java Private constructor in Junits - java

I've a class with few constants declared, initialized and I also have a private constructor.
For some reasons I'm writing Junits to achieve the code coverage.
Here I have used constructor.setaccessible(true) and I have initialized the class.
In the assert statement I'm expecting the length of the constructor to be 1.
I've achieved 100% code coverage for this class. But I'm quite not sure how. Can anyone please throw some light on this?
public class CommonConstants {
public static final String ABC= "ABC";
public static final String XYZ= "XYZ";
private CommonConstants() {}
}
#Test
public void stringTest() {
final Constructor<?>[] constructors = CommonConstants.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
try {
CommonConstants cc = (CommonConstants) constructors[0].newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Assert.assertEquals(1, constructors.length);
}

Related

Function Overloading with Subclass Parameters in Java [duplicate]

This question already has answers here:
Overloaded method selection based on the parameter's real type
(7 answers)
Closed 3 years ago.
I have a class that extends another class (In this case, it's an Exception):
public class NewTypeException extends Exception {
private String exceptionField;
public String getExceptionField() {
return exceptionField;
}
public void setExceptionField(String exceptionField) {
this.exceptionField = exceptionField;
}
public NewTypeException(String cause, String reason) {
super(cause);
exceptionField = reason;
}
}
And another class (for sake of example, lets call this PrintUtil) that has two methods with similar signatures, the only difference being the Exception type changes to the subclass:
void doStuff(Exception ex) {
System.out.println(ex.getMessage());
}
void doStuff(NewTypeException ex) {
System.out.println("New Type Exception");
System.out.println(ex.getExceptionField());
System.out.println(ex.getMessage());
}
In a lot of places in my code, I have a bunch of
try {
// code
} catch (Exception ex) {
printUtil.doStuff(ex);
}
After adding this new exception type, I want to have this line call the most specific method it can, depending on the argument. However, it seems when I test this, this will only use the method for Exception even if the runtime type fits another method (e.g. NewTypeException). Is there any way to do this other than replace hundreds of sections of
try {
// code
} catch (Exception ex) {
printUtil.doStuff(ex);
}
with
try {
// code
} catch (NewTypeException ex) {
printUtil.doStuff(ex);
} catch (Exception ex) {
printUtil.doStuff(ex);
}
? This seems like something really basic a OOP language should be able to do...
Not possible the way you're doing it. Method calls check the parameters arguments at compile time taking into account the declared types.
You may move the exception handling code somewhere else, but either you would need to instanceof or catch specific exceptions:
try {
// code
} catch (Exception ex) {
printUtil.handleExceptions(ex);
}
With utility class:
class PrintUtil {
public static handleExceptions(Exception e) {
try {
throw e;
} catch (NewTypeException ex) {
doStuff(ex);
} catch (AnotherTypeException ex) {
doStuff(ex);
}
}
...
}

I can't mock static method using Mockito and PowerMockito

I'm having trouble mocking a static method in a third-party library. I keep receiving a null-pointer exception when running the test, but I'm not sure why that is.
Here is the class and the void method that invokes the static method I'm trying to mock "MRClientFactory.createConsumer(props)":
public class Dmaap {
Properties props = new Properties();
public Dmaap() {
}
public MRConsumerResponse createDmaapConsumer() {
System.out.println("at least made it here");
MRConsumerResponse mrConsumerResponse = null;
try {
MRConsumer mrConsumer = MRClientFactory.createConsumer(props);
System.out.println("made it here.");
mrConsumerResponse = mrConsumer.fetchWithReturnConsumerResponse();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mrConsumerResponse;
}
}
Below is the test that keeps returning a null-pointer exception. The specific line where the null-pointer is being generated is: MRClientFactory.createConsumer(Mockito.any(Properties.class));
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.vismark.PowerMock.*")
public class DmaapTest {
#Test
public void testCreateDmaapConsumer() {
try {
Properties props = new Properties();
PowerMockito.mockStatic(MRClientFactory.class);
PowerMockito.doNothing().when(MRClientFactory.class);
MRClientFactory.createConsumer(Mockito.any(Properties.class));
//MRClientFactory.createConsumer(props);
Dmaap serverMatchCtrl = new Dmaap();
Dmaap serverMatchCtrlSpy = spy(serverMatchCtrl);
serverMatchCtrlSpy.createDmaapConsumer();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please follow this example carefully: https://github.com/powermock/powermock/wiki/MockStatic
Especially you are missing a
#PrepareForTest(Dmaap.class)
…to denote the class which does the static call.

Refactoring duplication with two different return types in java

Say I have these lines of code in all of my controllers:
public View ControllerClass() {
// ...
// some code in controller
SomeClass someClass;
try {
someClass = Util.getParam(
context.getEncryptedParam(), soemthignElse.getSomething());
} catch (SomeException ex) {
log.error(ex);
return viewBuilderFactory.view1.view();
} catch (AnotherException ex) {
return viewBuilderFactory.view2.view();
} catch (etc ...) {}
// use someClass
// ...
return viewBuilderFactory.view3.view();
}
In this case I'd have two different return types (void and view) if I want to move the duplication to its own method. What'd be a good approach here?
Your code is best restructured as follows:
public View ControllerClass() {
ViewBuilderFactoryView viewBuilderFactoryView;
try {
SomeClass someClass = Util.getParam(
context.getEncryptedParam(), soemthignElse.getSomething());
// use someClass
// ...
viewBuilderFactoryView = viewBuilderFactory.view3;
} catch (SomeException ex) {
log.error(ex);
viewBuilderFactoryView = viewBuilderFactory.view1;
} catch (AnotherException ex) {
viewBuilderFactoryView = viewBuilderFactory.view2;
} catch (etc ...) {}
return viewBuilderFactoryView.view();
}
In other words, if you successfully obtain a SomeClass, go ahead and use it, and afterwards return some View. If you do not successfully obtain a SomeClass, then just return some View.

Catching an exception when instantiating a class field

I want to instantiate a URL as a private field in a class, but I can't catch the MalformedURLException. I've tried using a static initialization block, but that doesn't work either. How do I solve this?
public class MyClass{
private final static URL DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
...
}
You will need to throw something in the case of an exception. An Error should do the job.
public class MyClass{
private static final URL DEFAULT_URL;
static {
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
} catch (java.net.MalformedURLException exc) {
throw new Error(exc);
}
}
...
}
In case an exception is thrown (it shouldn't be) the class will fail to initialse.
A simple workaround is to create a static method:
private final static URL DEFAULT_URL = getDefaultUrl();
private static URL getDefaultUrl() {
try {
return new URL("http://www.yadayada.com?wsdl");
} catch (Exception e) {
//what do you want to do here?
return null; //that is an option
throw new AssertionError("Invalid URL"); //that is another one
}
}
You can do it in the static block
public class MyClass {
private final static URL DEFAULT_URL;
static {
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
} catch (MalformedURLException e) {
}
}
Using static block initializer - you may catch exception inside the block.
However, I would not recommend to store it as final class field as URI. Place it as String constant and initialize in constructor or special init() intance method
Try below. you cannot use final keyword for below:
private static URL DEFAULT_URL = null;
static{
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

DRY for Exception Wrapping

I'm working on some server-side code that wraps all exceptions before passing them to the client side, due to this all client facing methods have the following code
try{
DoSomething();
} catch (ExceptionA e) {
throw new CustomException(AType, e);
} catch (ExceptionB e) {
throw new CustomException(BType, e);
} catch (Exception e) {
throw new CustomException(Unexpected, e);
}
to have this repeated in every method seems to violate the DRY principle and I was wondering what the best way to refactor it would be. For instance I was thinking a wrapper method such as:
private void wrapException(Exception e) {
if (e instanceof ExceptionA) {
throw new CustomException(AType, e);
}
etc...
Take a look at AspectJ soften exception.
Also look at Guava's Throwables.
There is also Lamboks sneaky exception.
The other option is to use Anonymous object instances aka closures.
public abstract class Wrapper {
public void execute() {
try {
// do some boiler plate before
this.wrap();
// do some boiler plate after.
} catch (ExceptionA | ExceptionB ex) {
Type t = determineType(ex);
throw new CustomException(t, ex);
}
}
public void abstract wrap();
}
Now in your code you do something like:
new Wrapper() {
public void wrap() {
DoSomething();
}
}.execute()
This is possible in Java7 and up:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Copy-paste example from above doc:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
This is one way to go about it:
Exception caughtEx = null;
String extraInfo = null;
try{
DoSomething();
} catch (ExceptionA e) {
caughtEx = e;
extraInfo = AType;
} catch (ExceptionB e) {
caughtEx = e;
extraInfo = BType;
} catch (Exception e) { // catching Exception is usually a bad idea, just let it bubble up without catching...
caughtEx = e;
extraInfo = Unexpected;
}
if (caughtEx != null) throw new CustomException(extraInfo, caughtEx);

Categories

Resources