Code executes actual instance instead of Powermock'ed instance? - java

I have a PowerMock
#Test
public void testDueSoonQueryOperation () {
try {
PowerMockito.whenNew(InitialContext.class).withNoArguments().
thenReturn((InitialContext) mockInitialContext);
} catch (Exception e) { e.printStackTrace(); }
try {
PowerMockito.when(lookup(anyString())).thenReturn(mockDataSource);
} catch (NamingException e) { e.printStackTrace(); }
try {
PowerMockito.when(mockDataSource.getConnection(anyString(), anyString())).thenReturn(mockDataConnection);
} catch (SQLException e) { e.printStackTrace(); }
QueryWorkItemHandler workItemHandler = new QueryWorkItemHandler();
BatchWorkItemHandler mockBatchHandler = PowerMockito.mock(BatchWorkItemHandler.class);
String dueIn7Days = "dueIn7Days";
HashMap<String, Object> taskDue7DaysMap = new HashMap<>();
taskDue7DaysMap.put(dueIn7Days,dueIn7Days);
PowerMockito.when(mockBatchHandler.handleMessageType(any(),
eq("SOON"), anyBoolean(), anyBoolean())).thenReturn(taskDue7DaysMap);
Map<String, Object> results = workItemHandler.doQueryOperation("SOON");
...
to test a class that uses JDBC to call a database. I mocked the Connection, DataSource, and InitialContext, but from the log messages the test seems to be using the real Connection, DataSource, and InitialContext. - why is it not using the mocked datasource, connection, and context? What do I need to add to have it use the mock's for these calls? If I replace a mock instance with (class of mock).class the compiler complains that the method does not exist for the class, e.g.,
PowerMockito.when((Context.class).lookup(Mockito.anyString()))
so I doubt it is simply a problem with my "when" clauses. The method being called in the class being test is
public class QueryWorkItemHandler extends AbstractLogOrThrowWorkItemHandler {
final static String dbJndiDataSource = System.getProperty("persistence.ds");
final static String dbUsername = System.getProperty("database.username");
final static String dbPassword = System.getProperty("database.password");
static BatchWorkItemHandler queryHelper = new BatchWorkItemHandler ();
public HashMap<String, Object> doQueryOperation(String messageType) {
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup(dbJndiDataSource);
Connection conn = ds.getConnection(dbUsername, dbPassword);
(up through the line that throws a null pointer exception because dbUsername is a property not set up in the mock.) If the Mock were being used it seems like the call to getConnection would be covered by
PowerMockito.when(mockDataSource.getConnection(anyString(),anyString())).thenReturn(mockDataConnection);

Related

Unchecked ThrowingSupplier for lambdas

How could I wrote a ThrowingSupplier with an unchecked method that could replace this part of code? I have really no idea how to start with it should it be an interface or rather a class.
try {
// get connection with the database
connection = dataSource.getConnection();
} catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
What I would like to get is something like
Connection connection = ThrowingSupplier.unchecked(dataSource::getConnection).get();
Any ideas how should it looks like? I am not sure if it should be an interface or a class I tried to wrote that, but then I could not create a static method unchecked and I would not to create new instance of that.
If I understand correctly, this is what you want:
public class ThrowingSupplier {
public static <T> Supplier<T> unchecked(Callable<T> callable) {
return () -> {
try {
return callable.call();
}
catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
};
}
// example usage:
public static void main(String[] args) {
DataSource dataSource = null;
Connection connection = ThrowingSupplier.unchecked(dataSource::getConnection).get();
}
}

Mocking constructor and a private function inside it using Mockito

I am in a scenario where I need to Unit test on class which is involving some bean formation and it require real data which I dont have, for more reference Below is the code.
the adapter class which I want to Mock
public class TIBCOAdapter {
public TIBCOAdapter(final GIAFProperties giafProperties) throws Exception {
if (giafProperties != null) {
this.giafProperties = giafProperties;
} else {
LOG.info("Error: No properties found");
}
init();
}
public void init() throws IOException {
factory = initializeQueueConnectionFactory();
requestQueue = initializeRequestQueue();
}
private QueueConnectionFactory initializeQueueConnectionFactory() {
final DurationRecord start = DurationLog.logBefore();
final JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiTemplate(new JndiTemplate(giafProperties.getProperties()));
bean.setJndiName(GIAFPropertyUtil.getPropertyString(giafProperties, "externalJndiName"));
try {
bean.afterPropertiesSet();
} catch (Exception e) {
throw new GIAFRuntimeException(e);
}
final ConnectionFactory targetConnectionFactory = (ConnectionFactory) bean
.getObject();
LOG.info("Got target connection factory: " + targetConnectionFactory);
final MultiCachingConnectionFactory factoryLocal = new MultiCachingConnectionFactory(
targetConnectionFactory, giafProperties);
DurationLog.logAfter(start);
return factoryLocal;
}
private Queue initializeRequestQueue() {
final JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiTemplate(new JndiTemplate(giafProperties.getProperties()));
bean.setJndiName(GIAFPropertyUtil.getPropertyString(giafProperties,
"request-queue"));
try {
bean.afterPropertiesSet();
} catch (Exception e) {
throw new GIAFRuntimeException(e);
}
return (Queue) bean.getObject();
}
}
The actual class where its object is created, which I don't want and that's why I want to mock creation of TIBCOAdapter
public class SomeClass {
public String getResponse(TestClientFilter testClientFilter) throws ICAException {
if (!filterValid(testClientFilter)) {
return null;
}
try {
Properties properties = new Properties(); // Sucess
GIAFProperties giafProperties = new GIAFProperties(properties, null); // sucess
addProperties(properties, testClientFilter); // sucess
TIBCOAdapter tibcoAdapter = new TIBCOAdapter(giafProperties); // ERROR This is the line which I want to mock
return (String) tibcoAdapter.invokeRequestResponse(testClientFilter.getMessage());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ICAException(e);
}
}
}
and this is my TEST
public class TestClientBusinessTest {
#Mock
private TIBCOAdapter tibco;
#InjectMocks
#Autowired
private SomeClass test;
#BeforeClass
public void setUp() throws NamingException {
MockitoAnnotations.initMocks(this);
}
private String returnStatement;
#Test(dataProvider = "getTestClientResponseBusiness", dataProviderClass = StaticDataProvider.class)
public void getResponse(TestClientFilter testClientFilter) throws Exception {
when(tibco.invokeRequestResponse(Matchers.any(TestClientFilter.class))).thenReturn(new Object());
test.getResponse(testClientFilter);
tibco.invokeRequestResponse(testClientFilter.getMessage());
}
}
These lines of code are making problem from TIBCOAdapters internal functions.
bean.setJndiTemplate(new JndiTemplate(giafProperties.getProperties()));
bean.setJndiName(GIAFPropertyUtil.getPropertyString(giafProperties, "externalJndiName"));

java.lang.ExceptionInInitializerError in Connection Factory

Hi Below is my code which will use as Connection Factory class. But i am getting java.lang.ExceptionInInitializerError. Please advice how to fix? I assume this is the trap because of static block, but not aware what exactly is this.
package j2ee.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class ConnFactory
{
public static Properties prop;
static
{
prop=new Properties();
try {
prop.load(ConnFactory.class.getClassLoader().getResourceAsStream("DBConfig.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}
private static ConnFactory instance = new ConnFactory();
public static final String URL = prop.getProperty("DEVURL");
public static final String USER = prop.getProperty("DEVUSER");
public static final String PASSWORD = prop.getProperty("DEVPASSWORD");
public static final String DRIVER_CLASS = prop.getProperty("DEVDRIVER_CLASS");
private ConnFactory() {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection createConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println("ERROR: Unable to Connect to Database.");
}
return connection;
}
public static Connection getConnection() {
return instance.createConnection();
}
public static void main(String a[])
{
Connection test=ConnFactory.getConnection();
System.out.println("Done");
}
}
Error is :
Caused by: java.lang.NullPointerException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at j2ee.dao.ConnFactory.<init>(ConnFactory.java:28)
at j2ee.dao.ConnFactory.<clinit>(ConnFactory.java:20)
private static ConnFactory instance = new ConnFactory(); // DRIVER_CLASS is null at this point
...
public static final String DRIVER_CLASS = ...;
You create an instance of ConnFactory before DRIVER_CLASS is initialized, therefore DRIVER_CLASS is null in the constructor of ConnFactory.
You need to reverse the order of these static field declarations:
public static final String DRIVER_CLASS = ...;
...
private static ConnFactory instance = new ConnFactory()
Actually, in my opinion it would be better to get rid of these static fields at all. Just make them non-static and initialize them in constructor.
You can also pass an instance of Properties into constuctor to decouple connection creation from storage of connection properties. If you do so, you will be able to use different sets of properties in different cases (for example, for test and production environments).

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();
}
}

"Could not find the main class, program will exit" while initializing class containing main()?

The class partially shown below contains a main method. When I run the code, I see a NullPointerException (NPE) and then an error message - "Could not find the main class, program will exit". My understanding is that if I get NPE, it means that the code is running, ie the JRE found a main method to begin execution, so why do I get the error message?
This is the console output
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at com.MyWorldDemo.getValue(MyWorldDemo.java:57)
at com.MyWorldDemo.<clinit>(MyWorldDemo.java:23)
Exception in thread "main"
In a nutshell:
username is stored in a properties file.
properties file is like this username=superman....etc
here is some code example
class MyClass {
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// this method will assign a value to my final variable username.
public static String getData(String props) {
String property = prop.getProperty(props);// ERROR HERE !!!
return property;
}
}
Initializing of static variables depends on its position in code (variables are initialized from top to bottom). In your code
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
prop object will be initialized after username in static block, but since to initialize username prop is necessary and its not initialized yet you get NPE. Maybe change your code to something like:
private static Properties prop = new Properties();
private final static String username = getData("username");
static {
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
You have a static initialization at line 23 of MyWorldDemo that is calling the method getValue, which is then causing a NPE at line 57, therefore the class cannot be instantiated, therefore the main method cannot be called. It probably looks something like:
class MyWorldDemo {
private static String foo = getValue("username");
private static Properties prop;
// This happens too late, as getValue is called first
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch(IOException ex) {
ex.printStackTrace();
}
}
// This will happen before static initialization of prop
private static String getValue(String propertyValue) {
// prop is null
return prop.getProperty(propertyValue);
}
public static void main(String args[]) {
System.out.println("Hello!"); // Never gets here
}
}

Categories

Resources