How to mock a Hibernate query using mockito - mockito

I am working on Power mockito for the first time.
Here is my code
#SuppressWarnings("unchecked")
public List<CurrencyBasedTotalCharges> getCurrencyBasedTotalChargesforCustomerSuperGroupforOperatingAccount(String customerSuperGroupId)
{
Session session =getSessionFromContext();
String sql = "SELECT ROUND(SUM(qst),2) ||'`'||ROUND(SUM(pst),2)||'`'||ROUND(SUM(gst),2)||'`'||ROUND(SUM(hst),2)||'`'||ROUND(SUM(converted_val),2)||'`'||currency " +
"FROM (" +
"SELECT CASE WHEN cr.oper_acc_curr is null or cr.oper_acc_curr='NA'" +
"THEN cr.charge_account_curr" +
"ELSE cr.oper_acc_curr END AS currency," +
"nvl ((select case when cr.DR_CR_FLAG='C' then -mcr.value else mcr.value end from mi_charge_record mcr where mcr.original_charge_record_id=cr.reference_id and substr(mcr.charge_code,3,length(mcr.charge_code))='GST'), 0" +
" ) AS gst," +
"nvl((select case when cr.DR_CR_FLAG='C' then -mcr.value else mcr.value end from mi_charge_record mcr where mcr.original_charge_record_id=cr.reference_id and substr(mcr.charge_code,3,length(mcr.charge_code))='PST'), 0" +
" ) AS pst," +
"nvl((select case when cr.DR_CR_FLAG='C' then -mcr.value else mcr.value end from mi_charge_record mcr where mcr.original_charge_record_id=cr.reference_id and substr(mcr.charge_code,3,length(mcr.charge_code))='QST'), 0" +
" ) AS qst," +
"nvl((select case when cr.DR_CR_FLAG='C' then -mcr.value else mcr.value end from mi_charge_record mcr where mcr.original_charge_record_id=cr.reference_id and substr(mcr.charge_code,3,length(mcr.charge_code))='HST'), 0" +
" ) AS hst," +
"CASE WHEN cr.DR_CR_FLAG='C'" +
" THEN (-cr.value) ELSE cr.value END AS converted_val," +
"cr.reference_id FROM mi_charge_record cr, mi_bl_billing_preference bp, account acc, customer c," +
"mii_customer_group cg"+
"WHERE acc.account_number=cr.account_number AND acc.customer_id=c.customer_id AND c.customer_group_id=cg.id AND cg.customer_super_group_id=:superGroupId AND" +
"to_date(cr.BILLED_DATE) BETWEEN to_date(bp.billing_cycle_start_date,'yyyymmdd') AND to_date(bp.billing_cycle_end_date,'yyyymmdd') AND CR.PRODUCT_SHORT_NAME<> 'TAX'" +
"AND CR.IS_COST <> 'Y'"+
") z" +
"GROUP BY currency having SUM(ROUND(converted_val,2)) != 0";
List<String> totalchargedetails=session.createSQLQuery(sql).setString("superGroupId", customerSuperGroupId).list();
LinkedHashMap<String, String> paramMap=new LinkedHashMap<>();
paramMap.put(CHARGE_LEVEL, CHARGE_BY_OPERATING_ACCOUNT);
paramMap.put(LINKED_ENTITY_GUID, customerSuperGroupId);
paramMap.put(STATEMENT_LEVEL, CUSTOMER_SUPER_GROUP_STATEMENT_LEVEL);
return getFinalCurrencyBasedTotalCharges(setCurrencyBasedTotalCharges(totalchargedetails),paramMap);
}
I am trying to test above functionality using mockito as below:
public void getCurrencyBasedTotalChargesforCustomerGroupforOperatingAccountTest() throws Exception
{
String customerGroupId = "CG-100001-01";
PowerMockito.doReturn(session).when(implStatementDAOImpl, "getSessionFromContext");
Mockito.when(query.setString(anyString(), anyString())).thenReturn(query);
Mockito.when(session.createQuery(anyString())).thenReturn(query);
Mockito.doReturn(entityObjectBuilder.currencyBasedTotalCharges()).when(query).list();
List<String> totalchargedetails = new ArrayList<String>();
List<CurrencyBasedTotalCharges> test = implStatementDAOImpl.getCurrencyBasedTotalChargesforCustomerGroupforOperatingAccount(customerGroupId);
//given( implStatementDAOImpl.getCurrencyBasedTotalChargesforCustomerGroupforOperatingAccount(customerGroupId).t, session)).willReturn(new ArrayList<CurrencyBasedTotalCharges>());
//Assert.assertFalse(test.isEmpty());
Mockito.verify(session).createQuery(anyString());
Mockito.verify(query).setString(anyString(), anyString());
Mockito.verify(query).list();
System.out.println(test);
}
I am getting NullPointer exception on session.createQuery line. Plesae guide me how shall I mock this and test.
Thanks.

where is session initialized?
You could do the initialization as follows:
#Mock
private Session session;
#Before
public void setup(){
MockitoAnnotations.initMocks(this);
}
It is important to init the mocks when using Annotations for mocking/spying
Another option is to init the session like this, e.g directly in your test method:
Session session = Mockito.mock(Session.class);

Related

search(query) throws NullPointerException

public List<DHProductLookupModel> findProductbyCCsapProductId(final String code)
{
final String queryString = "SELECT {p:" + DHProductLookupModel.SAPPRODUCTID + "}" + "FROM{" + DHProductLookupModel._TYPECODE
+ " AS p}" + "WHERE" + "{p:" + DHProductLookupModel.SAPPRODUCTID + "}=?code ";
final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString);
query.addQueryParameter("code", code);
return flexibleSearchService.<DHProductLookupModel> search(query).getResult();
}
search(query) throws Null Pointer Exception, how to handle this?
Output:
Caused by: java.lang.NullPointerException
at de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService.getJaloResult(DefaultFlexibleSearchService.java:396) ~[coreserver.jar:?]
at de.hybris.platform.servicelayer.search.impl.DefaultFlexibleSearchService.search(DefaultFlexibleSearchService.java:168) ~[coreserver.jar:?]
at com.cancom.core.productlookup.dao.impl.CCProductLookupDaoImpl.findProductbyCCmanufacturerProductId(CCProductLookupDaoImpl.java:39) ~[classes/:?]
at com.cancom.core.productlookup.service.impl.CCProductLookupServiceImpl.getProductforCCmanufacturerProductId(CCProductLookupServiceImpl.java:37) ~[classes/:?]
Thanks!
Change your flexible search query from
final String queryString = "SELECT {p:" + DHProductLookupModel.SAPPRODUCTID + "}" + "FROM{" + DHProductLookupModel._TYPECODE
+ " AS p}" + "WHERE" + "{p:" + DHProductLookupModel.SAPPRODUCTID + "}=?code ";
to
final String queryString = "SELECT {p:" + DHProductLookupModel.PK + "}" + "FROM{" + DHProductLookupModel._TYPECODE
+ " AS p}" + "WHERE" + "{p:" + DHProductLookupModel.SAPPRODUCTID + "}=?code ";
You should send DHProductLookupModel.PK in search result.
In your case, you can use getModelsByExample of flexibleSearchService instead of writing the query.
Your method will be like
public List<DHProductLookupModel> findProductbyCCsapProductId(final String code)
{
DHProductLookupModel dhProductLookupModel = new DHProductLookupModel();
dhProductLookupModel.setSapProductID(code);
return getFlexibleSearchService().getModelsByExample(dhProductLookupModel);
}
find the example here
Thanks everyone!
I found the Problem. It was in my spring.I just had to put :
<context:component-scan base-package="myPackage"/>
I changed also the query with DHProductLookupModel.PK for safety. Now it´s work!

xpages ftsearch documents from an interval of dates

I made an xpage element for ftsearch using a tutorial from IBM
My request: is there possible having 2 date fields ( as input requirements for the search ) to find those documents having the creation date inside the interval consisting of those 2 dates?
Should I create a computed field dtCreated where I will store the creation date and then in the search property of the view I should add something like this:
var tmpArray = new Array("");
var cTerms = 0;
if (sessionScope.searchDate1) && (sessionScope.searchDate2) {
tmpArray[cTerms++] = "(Field dtCreated > \"" + sessionScope.searhcDate1 + "\")" && "(Field dtCreated < \"" + sessionScope.searhcDate2 + "\")";
}
....
....
Or there is another alternative?
My 2 session variables are having Short (5/5/14) Date format. Also, my default value for those 2 dates (session variables) are "" but of course I add some values before clicking the Submit button.
Thanks for your time!
You can use the special field _creationDate as creation date (see answer from Tommy). Based on this the following example query will work in the Notes client:
Field _creationDate > 01-01-2014 AND Field _creationDate < 01-03-2014
In order to get this query to work with your specific code do this:
var tmpArray = new Array("");
var cTerms = 0;
var dateFormatter = new java.text.SimpleDateFormat( "dd-MM-yyyy" );
if (sessionScope.searchDate1) && (sessionScope.searchDate2) {
tmpArray[cTerms++] = "Field _creationDate > " + dateFormatter.format(sessionScope.searchDate1) + " AND Field _creationDate < " + dateFormatter.format(sessionScope.searchDate2);
}
If you want to do an FTSearch, _CreationDate can be used
Documentation (scroll to Searching for Header Information):
http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=%2Fcom.ibm.designer.domino.main.doc%2FH_CUSTOMIZING_SEARCH_FORMS_7304.html
E.g. (there might be typos):
tmpArray[cTerms++] = "(Field _creationDate>" + sessionScope.searhcDate1 + ") AND (Field _creationDate<" + sessionScope.searhcDate2 + ")";
Or my preferred syntax:
tmpArray[cTerms++] = "[_creationDate>" + sessionScope.searhcDate1 + "] AND [_creationDate<" + sessionScope.searhcDate2 + "]";
To build on Tommy's answer:
Specifically, try "yyyy/m/d" as the format. If those values in sessionScope are java.util.Date (the type that date fields use), you could try something like this (typing off the top of my head, not in an app, so my apologies for typos):
var tmpArray = [];
var cTerms = 0;
if(sessionScope.searchDate1 && sessionScope.searchDate2) {
var formatter = new java.text.SimpleDateFormat("yyyy/M/d");
tmpArray[cTerms++] = "[_CreationDate] >= " + formatter.format(sessionScope.searchDate1) + " and [_CreaationDate] <= " + formatter.format(sessionScope.searchDate2)
}
What you want to end up with is a FT query like:
[_CreationDate] >= 2014/1/1 and [_CreationDate] <= 2014/2/1

Unable to test the Transient Fault Handling Application Block for Azure

I'm having trouble performing a simple test of the Transient Fault Handling Application Block, so I must be missing something silly.
Based on the information in http://msdn.microsoft.com/en-us/library/hh680927(v=pandp.50).aspx and
http://azuretable.blogspot.com/2012/08/unit-testing-transient-errors-in-azure.html I have created the mock class below:
Public Class DBUtils_TestRetryPolicy
' see http://msdn.microsoft.com/en-us/library/hh680927(v=pandp.50).aspx
' see http://azuretable.blogspot.com/2012/08/unit-testing-transient-errors-in-azure.html
Public Class TransientMock
Implements ITransientErrorDetectionStrategy
Public Function IsTransient(ex As System.Exception) As Boolean Implements Microsoft.Practices.TransientFaultHandling.ITransientErrorDetectionStrategy.IsTransient
Return (True)
End Function
End Class
Private Shared mockExceptionCounter As Integer = 0
Private Shared retryLog As String = ""
Private Sub ThrowException()
mockExceptionCounter += 1
Throw New Exception("This is as mock exception to test retries")
End Sub
Public Function TestRetryLogic() As String
Dim theRetryStrategy = New Incremental(6, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)) ' should result in retries at 0, 1, 3, 5, 7, 9 seconds (25 seconds total)
theRetryStrategy.FastFirstRetry = True
Dim theRetryPolicy = New RetryPolicy(Of TransientMock)(theRetryStrategy)
AddHandler theRetryPolicy.Retrying, AddressOf OnMockConnectionRetry
mockExceptionCounter = 0
retryLog = ""
Try
theRetryPolicy.ExecuteAction(New System.Action(AddressOf ThrowException))
Catch ex As Exception
' here we should have the last exception thrown after all the retries
Dim a As Integer = 231234234
End Try
Return (retryLog)
End Function
Private Sub OnMockConnectionRetry(sender As Object, e As RetryingEventArgs)
retryLog += DateTime.UtcNow.ToString + " [" + mockExceptionCounter.ToString() + "] -> CurrentRetryCount [" + Cstr(e.CurrentRetryCount) + "]" + "Delay (ms) [" + CStr(e.Delay.TotalMilliseconds) + "]" + "LastException [" + e.LastException.Message + "]"
End Sub
End Class
All I do in my code is to instantiate this class and call TestRetryLogic().
I ran the Visual Studio debugger expecting to see a few retries, but what I get is a popup from Visual Studio saying "Exception was unhandled by user code". This happens as soon as I throw inside the method ThrowException(). Of course no retries seem to be happening.
What am I missing?
EDIT: I was failing to cast to string inside OnMockConnectionRetry, so I assume I was throwing an exception inside an (already "running") exception-handling block. By using the tip from Petar I was able to see (and fix) this little problem and now the retries are working as expected.
You need to turn off Common Language Runtime Exceptions by un-checking the User-unhandled option to not get interrupted by VS. This is located under Debug/Exceptions menu.

Error is "Object reference not set to an instance of an object"

i have a problem, when i m run my code then error is occured that "Object reference not set to an instance of an object."
plz suggest me regarding that.
Code
protected void btn_Save_Click(object sender, EventArgs e)
{
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/eTimeTrackLite1.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "insert into Employees ([EmployeeName],EmployeeCode,DeviceCode,Company,Department,Designation,Grade,Team,Location,EmploymentType,Category,HolidayGroup,ShiftGroup,ShiftRoster,Dateofjoining,Dateofconfirmation,Status,DateofResigning,[Sex]) values ('" + txt_empname.Text + "','" + txt_code.Text + "', '" + txt_dcode.Text + "', '" + dp_company.SelectedItem.ToString() + "', '" + dp_department.SelectedItem.ToString() + "', '"+dp_designation.SelectedItem.ToString()+"', '"+dp_grade.SelectedItem.ToString()+"', '"+dp_team.SelectedItem.ToString()+"', '"+dp_location.SelectedItem.ToString()+"', '"+dp_emptype.SelectedItem.ToString()+"', '"+dp_category.SelectedItem.ToString()+"', '"+dp_holigroup.SelectedItem.ToString()+"', '"+dp_shiftgroup.SelectedItem.ToString()+"', '"+dp_shiftroster.SelectedItem.ToString()+"', '"+dp_day.SelectedItem.ToString()+"', '"+dp_month.SelectedItem.ToString()+"', '"+dp_year.SelectedItem.ToString()+"', '"+dp_cday.SelectedItem.ToString()+"', '"+dp_cmonth.SelectedItem.ToString()+"', '"+dp_cyear.SelectedItem.ToString()+"', '"+dp_status.SelectedItem.ToString()+"', '"+dp_rday.SelectedItem.ToString()+"', '"+dp_rmonth.SelectedItem.ToString()+"', '"+dp_ryear.SelectedItem.ToString()+"', '"+rdbtn_male.Checked.ToString()+"', '"+rdbtn_female.Checked.ToString()+"')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
BindGridData();
}
"Thanks"
In order to avoid this kind of problems, don't use ToString is there is a risk of the calling object to be null, use Convert.ToString() instead.
http://msdn.microsoft.com/en-us/library/system.convert.tostring.aspx

Wait for input from the user in C#

How can I make a program stop in order to insert inputs, such as username and password,
"UserId=te; PWD=t57; database=ph3;");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection conDatabase = new MySqlConnection("Data Source=localhost;" +
"Persist Security Info=yes;" +
"UserId=te; PWD=t57; database=ph3;");
conDatabase.Open();
// MySqlCommand cmdDatabase = new MySqlCommand("DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc;", conDatabase);
string[] arr = new string[12];
arr[0] = "UPDATE `member` SET `amphurecode`= SUBSTRING(member.own,3,4)";
arr[1] = "UPDATE `member` SET `provincecode`= SUBSTRING(member.own,3,2)";
arr[2] = "DROP TABLE IF EXISTS `q_mem_tim`; create table q_mem_tim as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.novote, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE";
arr[10] = "UPDATE q_mem_birth SET agec = CASE WHEN y < 10 THEN '¿' WHEN y > 10 and y < 20 and Sex='¿' THEN '¿¿' WHEN y > 10 and y < 20 and Sex='¿' THEN '¿¿' ELSE '¿¿' END";
arr[11] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT q_mem_tim.idmember,q_mem_tim.own,q_mem_tim.PROVINCE_NAME,q_mem_tim.AMPHUR_NAME,q_mem_tim.novote,q_mem_tim.Sname,q_mem_tim.Ssurname,q_mem_tim.Hno,q_mem_tim.Moo,q_mem_tim.Sex,q_mem_tim.tambol,q_mem_tim.dateofbirth,q_mem_tim.migratedate,q_mem_tim.y,q_mem_tim.d,q_mem_tim.agec FROM q_mem_tim where q_mem_tim.dateofbirth is not null and q_mem_tim.dateofbirth != '00000000' and day(q_mem_tim.dateofbirth) != '00' and day(q_mem_tim.dateofbirth) > 0 and day(q_mem_tim.dateofbirth) < 11 and month(q_mem_tim.dateofbirth) != '00' and month(q_mem_tim.dateofbirth) > 8 and month(q_mem_tim.dateofbirth) < 10 order by tambol,Moo, month(dateofbirth),day(dateofbirth) ";
foreach (string s in arr)
{
Console.WriteLine(s);
MySqlCommand cmdDbase = new MySqlCommand((s), conDatabase);
cmdDbase.CommandTimeout = 500;
cmdDbase.ExecuteNonQuery();
}
conDatabase.Close();
}
}
}
You probably want to use the Console.ReadLine(); method. For more details, see Console.ReadLine Method (MSDN).
Something like this:
Console.WriteLine("Enter username");
string uname=Console.ReadLine();

Resources