How to hit the database from junit using JPA - junit

I am writing junit test case, how to hit the database from junit using jpa.
I wrote the code for but got the following exception
javax.persistence.PersistenceException: No Persistence provider for EntityManager named smsPU
I added provide in src/test/resources/META-INF/persistent.xml file, But i got the that error.
I am posting the my code also please check where is the wrong in this code.
public class SmsBeanTest {
private SmsBean smsBean;
private SmsNotification notification;
private EntityManagerFactory entity;
private EntityManager em;
#Before
public void setUp() throws Exception {
String CONFIG_ATTR_NAME = "webappConfig";
smsBean = new SmsBean();
ServletContext ctx = mock(ServletContext.class);
Configuration config = new Configuration();
config.initProperties("syniverse-sms.properties");
when(ctx.getAttribute(CONFIG_ATTR_NAME)).thenReturn(config);
smsBean.setServletContext(ctx);
**//em = mock(EntityManager.class);
Properties prop = new Properties();
// Ensure RESOURCE_LOCAL transactions is used.
prop.put(TRANSACTION_TYPE,
PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal connection pool
prop.put(JDBC_DRIVER, "com.mysql.jdbc.Driver");
prop.put(JDBC_URL, "jdbc:mysql://localhost:3306/platform_service_db");
prop.put(JDBC_USER, "root");
prop.put(JDBC_PASSWORD, "root");
prop.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
"src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar");
entity = Persistence.createEntityManagerFactory("smsPU", prop);
System.out.println(entity);
em = entity.createEntityManager(prop);
smsBean.setEm(em);**
// doNothing().when(em).persist(notification);
smsBean.init();
notification = new SmsNotification();
}
#After
public void tearDown() throws Exception {
smsBean = null;
notification = null;
//entity.close();
//em.close();
}
#Test
public void testSendSms() {
SmsNotificationDTO sms = new SmsNotificationDTO();
sms.setToAddress("9985291980");
sms.setMessage("Sending Message...");
try {
SyniverseDispatcher disp = mock(SyniverseDispatcher.class);
SyniverseResponse resp = new SyniverseResponse();
resp.setResponseStr("1234");
String smsTo = notification.getDestination();
String smsMsg = notification.getMessage() + new Date().getTime();
String urlStr = smsBean.getHostname() + "?user=" + smsBean.getUser() + "&pass=" + smsBean.getPass() + "&smsfrom=" + smsBean.getShortCode() + "&smsto=" + sms.getToAddress() + "&smsmsg=" + sms.getMessage();
SyniverseRequest req = new SyniverseRequest();
req.setRequestURL(urlStr);
when(disp.dispatch(req)).thenReturn(resp);
smsBean.sendSms(sms);
assertNotNull(sms.getToAddress());
assertEquals(10, sms.getToAddress().length());
assertNotNull(sms.getMessage());
assertEquals("1234", resp.getResponseStr());
} catch (SmsException e) {
fail(e.getMessage());
}
}
}
please help me,

it can't find the persistance.xml because you have it incorrectly defined. "src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar" the jar file shouldn't be listed.

Related

Spying method calls the actual Method

I am writing a JUnit with Mockito. But on the line
when(encryptDecryptUtil.getKeyFromKeyStore(any(String.class))).thenReturn(keyMock);
It calls the actual method, which is causing the test failure. Interesting point is that it directly makes the actual call at start of the test case when when()...thenReturn() statemnts gets executed. Can you please tell me how I can fix this? My test is as per below
#Test
public void testDecryptData_Success() throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
encryptDecryptUtil = spy(new EncryptDecryptUtil());
Key keyMock = Mockito.mock(Key.class);
when(encryptDecryptUtil.getKeyFromKeyStore(any(String.class))).thenReturn(keyMock);
String inputData = "TestMessage";
String version = GetPropValues.getPropValue(PublisherConstants.KEYSTORE_VERSION);
byte[] enCryptedValue= new byte[] {9,2,5,8,9};
Cipher cipherMock = Mockito.mock(Cipher.class);
when(Cipher.getInstance(any(String.class))).thenReturn(cipherMock);
when(cipherMock.doFinal(any(byte[].class))).thenReturn(enCryptedValue);
String encryptedMessage = encryptDecryptUtil.encryptData(inputData);
assert(encryptedMessage.contains(version));
assertTrue(!encryptedMessage.contains(inputData));
}
On the third line it self, it calls the actual method.
Main code is as per below.
public class EncryptDecryptUtil {
private String publicKeyStoreFileName =
GetPropValues.getPropValue(PublisherConstants.KEYSTORE_PATH);
private String pubKeyStorePwd = "changeit";
private static final String SHA1PRNG = "SHA1PRNG";
private static final String pubKeyAlias="jceksaes";
private static final String JCEKS = "JCEKS";
private static final String AES_PADDING = "AES/CBC/PKCS5Padding";
private static final String AES = "AES";
private static final int CONST_16 = 16;
private static final int CONST_0 = 0;
private static final String KEY_STORE = "aes-keystore";
private static final String KEY_STORE_TYPE = "jck";
private static final Logger logger = Logger.getLogger(KafkaPublisher.class);
public Key getKeyFromKeyStore( String keystoreVersion) {
KeyStore keyStore = null;
Key key = null;
try {
keyStore = KeyStore.getInstance(JCEKS);
FileInputStream stream = null;
stream = new FileInputStream(publicKeyStoreFileName+KEY_STORE+PublisherConstants.UNDERSCORE+keystoreVersion+PublisherConstants.DOT+KEY_STORE_TYPE);
keyStore.load(stream, pubKeyStorePwd.toCharArray());
stream.close();
key = keyStore.getKey(pubKeyAlias, pubKeyStorePwd.toCharArray());
} catch (KeyStoreException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
logger.error("Error Inside getKeyFromKeyStore, Exception = " + e);
e.printStackTrace();
} catch (CertificateException e) {
logger.error("Error Inside getKeyFromKeyStore, Exception = " + e);
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
logger.error("Error Inside getKeyFromKeyStore, Exception = " + e);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
logger.error("Error Inside getKeyFromKeyStore, Exception = " + e);
e.printStackTrace();
} catch (IOException e) {
logger.error("Error Inside getKeyFromKeyStore, Exception = " + e);
e.printStackTrace();
}
return key;
}
public String encryptData(String data) {
String keystoreVersion = GetPropValues.getPropValue(PublisherConstants.KEYSTORE_VERSION);
SecretKey secKey = new SecretKeySpec(getKeyFromKeyStore(keystoreVersion).getEncoded(), AES);
String base64EncodedEncryptedMsg = null;
Cipher cipher = null;
try { ------- Logic -------------------}
catch() { }
}
}
Have a look at the "Important gotcha on spying real objects" section of the Spy documentation.
Essentially, you cannot use the when(...).thenReturn(...) pattern with Spies, because as you have discovered, it calls the real method!
Instead, you use a different pattern which does exactly the same thing:
doReturn(...).when(spy).someMethod();
So, for your example:
doReturn(keyMock).when(encryptDecryptUtil).getKeyFromKeyStore(any(String.class));
Some advice which is unrelated to your question: If I read your code correctly, then EncryptDecryptUtil is the class that you are testing. As a general rule, you should not mock, stub, or spy on the object that you are actually testing, because then you are not testing the true object. You are actually testing a version of the object creating by the Mockito library. Furthermore, it's an uncommon pattern which will make your tests hard to read and maintain. If you find yourself having to do this, then the best thing would be to refactor your code so that the methods you are mocking (or spying on) and the methods you are testing are in different classes.

Quasar multi fibers warning

I am new to quasar and I tried doing this.
Basically I get a warning the fiber is blocking a thread. Why ? can I not do something like below ?
Thanks
//in my my testclass I have this
String websites[] = {"http://www.google.com",""http://www.lol.com",""http://www.somenoneexistantwebsite.com"};
for(int i=0; i < websites.length ; i++){
TestApp.getWebsiteHTML(websites[i]);
}
//in TestApp
public static void getWebsiteHTML(String webURL) throws IOException, InterruptedException, Exception {
new Fiber<Void>(new SuspendableRunnable() {
#Override
public void run() throws SuspendExecution, InterruptedException {
WebInfo mywi = new WebInfo();
mywi.getHTML(webURL);
}
}).start().join();
}
//in WebInfo
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Have a look at the "Runaway fibers" sub-section in the docs.
HttpURLConnection is thread-blocking so in order to avoid stealing threads from the fiber scheduler for too much time (which risks killing your Quasar-based application's performance) you should rather use an HTTP client integrated with Quasar (or integrate one yourself).

Unable to switch to WEBVIEW using Selendroid, getting WebDriverException

Im trying to automate hybrid application using Selendroid.
Im getting exception at "driver.switchTo().window("WEBVIEW").
Below is the code.
WebElement uname;
WebElement password;
#BeforeClass
public static void setUp() throws Exception{
System.out.println("Set up in progress");
SelendroidConfiguration config = new SelendroidConfiguration();
config.addSupportedApp("D:DJ/HDFC/iAgent.apk");
if(selendroidServer!=null){
selendroidServer.stopSelendroid();
}
selendroidServer = new SelendroidLauncher(config);
selendroidServer.launchSelendroid();
SelendroidCapabilities capa = new SelendroidCapabilities();
capa.setAut("com.hdfclife.msd:4.85");
capa.setEmulator(false);
//capa.setPlatformVersion(DeviceTargetPlatform.ANDROID19);
driver = new SelendroidDriver(capa);
}
#Test
public void selendroidTest() throws InterruptedException{
System.out.println("Hello.. mSD under Test -- " + driver.getCurrentUrl());
//driver.switchTo().activeElement();
driver.switchTo().window("WEBVIEW");
Thread.sleep(10000);
uname = driver.findElement(By.name("username"));
uname.sendKeys("110105");
Thread.sleep(3000);
password = driver.findElement(By.name("password"));
password.sendKeys("Hdfc#123");
Thread.sleep(3000);
WebElement loginBtn = driver.findElement(By.id("loginButton"));
loginBtn.click();
Thread.sleep(3000);
}
#AfterClass
public static void tearDown(){
selendroidServer.stopSelendroid();
driver.quit();
}
Below is the error displaying.
org.openqa.selenium.WebDriverException: CATCH_ALL: java.lang.NullPointerException
at io.selendroid.server.model.internal.WebViewHandleMapper.getWebViewByHandle(WebViewHandleMapper.java:49)
at io.selendroid.server.model.SelendroidWebDriver.init(SelendroidWebDriver.java:310)
at io.selendroid.server.model.SelendroidWebDriver.(SelendroidWebDriver.java:87)
Can any one help on this.
Thanks,
Dheeraj
Check with the WEBVIEW_01 and WEBVIEW_02 along with WEBVIEW in driver.switchto statement.
The identifier of web view can also be like above.

Junit Test unable to load Properties File

I'm trying to run a simple test to check values in a properties file which I've saved in the src/test/resources folder of my Maven project but the JUnit test is failing. My test is picking up the File OK but it doesn't return the expected value as the file doesn't look like its getting loaded. Anyone else have a similar issue? My code/test are as follows:
My Application Context File:
<bean id="myProps" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:test.properties"/>
</bean>
My Code:
#Resource(name = "myProps") private Properties myProps;
#Value("#{myProps['totalNumberOfChanges']}") private String totalNumberOfChangesStr;
#Value("#{myProps['delayTime']}") private String delayTimeStr;
public void parseAttributesFromConfigFile() {
String methodName = "parsePropertyAttributesFromConfigFile";
try {
totalNumberOfChanges = Integer.parseInt(totalNumberOfChangesStr);
delayTime = Integer.parseInt(delayTimeStr);
numEntriesToIterateThru = (totalNumberOfChanges / delayTime);
} catch (NumberFormatException nfe) {
LOGGER.error(methodName, "", "Number Format Exception Occured" + nfe.getMessage());
}
}
My Junit Test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:META-INF/spring/Testpu.xml" })
public class ConfigPropertiesTest {
private final int NUM_ENTRIES_TO_ITERATE_THRU = 100;
private final int TOTAL_NUMBER_OF_CHANGES = 100000;
private final int DELAY_TIME = 1000;
private ConfigProperties configProperties;
#Before
public void setUp() throws Exception {
configProperties = new ConfigProperties();
}
#Test
public final void testParseAttributesFromConfigFileIsCalled() {
configProperties.parseAttributesFromConfigFile();
int numEntriesToIterateOver = configProperties.getNumEntriesToIterateThru();
assertEquals(numEntriesToIterateOver, NUM_ENTRIES_TO_ITERATE_THRU);
int numberOfChanges = configProperties.getTotalNumberOfChanges();
assertEquals(numberOfChanges, TOTAL_NUMBER_OF_CHANGES);
int delayTime = configProperties.getDelayTime();
assertEquals(delayTime, DELAY_TIME);
}
}
You are creating the ConfigProperties class in your Before method. If you want Spring to populated values based on annotations the bean must be created as part of the Spring context. If you have an instance of ConfigProperties in your Spring context, load that instance into your test using #Autowired

Ehcache hangs in test

I am in the process of rewriting a bottle neck in the code of the project I am on, and in doing so I am creating a top level item that contains a self populating Ehcache. I am attempting to write a test to make sure that the basic call chain is established, but when the test executes it hands when retrieving the item from the cache.
Here are the Setup and the test, for reference mocking is being done with Mockito:
#Before
public void SetUp()
{
testCache = new Cache(getTestCacheConfiguration());
recordingFactory = new EntryCreationRecordingCache();
service = new Service<Request, Response>(testCache, recordingFactory);
}
#Test
public void retrievesResultsFromSuppliedCache()
{
ResultType resultType = mock(ResultType.class);
Response expectedResponse = mock(Response.class);
addToExpectedResults(resultType, expectedResponse);
Request request = mock(Request.class);
when(request.getResultType()).thenReturn(resultType);
assertThat(service.getResponse(request), sameInstance(expectedResponse));
assertTrue(recordingFactory.requestList.contains(request));
}
private void addToExpectedResults(ResultType resultType,
Response response) {
recordingFactory.responseMap.put(resultType, response);
}
private CacheConfiguration getTestCacheConfiguration() {
CacheConfiguration cacheConfiguration = new CacheConfiguration("TEST_CACHE", 10);
cacheConfiguration.setLoggingEnabled(false);
return cacheConfiguration;
}
private class EntryCreationRecordingCache extends ResponseFactory{
public final Map<ResultType, Response> responseMap = new ConcurrentHashMap<ResultType, Response>();
public final List<Request> requestList = new ArrayList<Request>();
#Override
protected Map<ResultType, Response> generateResponse(Request request) {
requestList.add(request);
return responseMap;
}
}
Here is the ServiceClass
public class Service<K extends Request, V extends Response> {
private Ehcache cache;
public Service(Ehcache cache, ResponseFactory factory) {
this.cache = new SelfPopulatingCache(cache, factory);
}
#SuppressWarnings("unchecked")
public V getResponse(K request)
{
ResultType resultType = request.getResultType();
Element cacheEntry = cache.get(request);
V response = null;
if(cacheEntry != null){
Map<ResultType, Response> resultTypeMap = (Map<ResultType, Response>) cacheEntry.getValue();
try{
response = (V) resultTypeMap.get(resultType);
}catch(NullPointerException e){
throw new RuntimeException("Result type not found for Result Type: " + resultType);
}catch(ClassCastException e){
throw new RuntimeException("Incorrect Response Type for Result Type: " + resultType);
}
}
return response;
}
}
And here is the ResponseFactory:
public abstract class ResponseFactory implements CacheEntryFactory{
#Override
public final Object createEntry(Object request) throws Exception {
return generateResponse((Request)request);
}
protected abstract Map<ResultType,Response> generateResponse(Request request);
}
After wrestling with it for a while, I discovered that the cache wasn't being initialized. Creating a CacheManager and adding the cache to it resolved the problem.
I also had a problem with EHCache hanging, although only in a hello-world example. Adding this to the end fixed it (the application ends normally).
CacheManager.getInstance().removeAllCaches();
https://stackoverflow.com/a/20731502/2736496