I am trying to Test a method but it has a global variable which is null, Please guide me so I can assign value to global variable i.e. a Map
My Junit:
public class ErrorTest {
#Mock
private DataSource db;
#Mock
private JdbcTemplate jdbcTemplate;
#InjectMocks
private RateServiceImpl rateService = new RateServiceImpl();
#Mock
private RaterDao raterDao;
#Resource
private MessageSource msg ;
#Mock
Map<String, StringAttribute> errorMap = new HashMap<String, StringAttribute>();
#Before
public void setup() throws IOException, InterruptedException {
MockitoAnnotations.initMocks(this);
MockMvcBuilders.standaloneSetup(rateService).build();
}
#Test
public void findAllErrors() throws Exception {
String error;
List<Error> erList = new ArrayList<>();
Error er27 = new ErrorImpl("27",
"No detail found",
"Please enter detail.");
erList.add(er27);
Error er22 = new ErrorImpl("1",
"Maximum number exceeded",
"Please contact Technical Support.");
erList.add(er22);
for (int index = 0; index < erList.size(); index++) {
StringAttribute st = new StringAttributeImpl();
st.setName(erList.get(index).getDescription());
st.setValue(erList.get(index).getResolution());
errorMap.put(erList.get(index).getCode(), st);
}
List<Error> errorList = raterDao.findAllErrors();
assertThat(errorList, is(notNullValue()));
StringAttribute map27 = errorMap.get("27");
Mockito.when(rateService.findRwxlClientError("27")).thenReturn(map27);
StringAttribute map22 = errorMap.get("22");
Mockito.when(rateService.findRwxlClientError("22")).thenReturn(map22);
assertTrue("ParseShipment failed", map27.getName().equals("No detail found"));
assertTrue("ParseShipment failed", map22.getName().equals("Please contact Technical Support."));
}
}
My Main Class:
#Service
public class RateServiceImpl implements RateService {
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private RaterDao raterDao;
private Map<String, StringAttribute> errorMap = new HashMap<String, StringAttribute>();
#Resource
private MessageSource msg;
#PostConstruct
public void init() throws Exception {
**errorMap** = findAllClientErrors();
}
public Map<String, StringAttribute> findAllClientErrors() throws Exception {
List<Error> errorList = raterDao.findAllClientErrors();
for (int index = 0; index < errorList.size(); index++) {
StringAttribute st = new StringAttributeImpl();
st.setName(errorList.get(index).getDescription());
st.setValue(errorList.get(index).getResolution());
errorMap.put(errorList.get(index).getCode(), st);
}
return errorMap;
}
#Override
public StringAttribute findClientError(String code) throws Exception {
StringAttribute error = new StringAttributeImpl();
if (code.equals(Constants.ERROR_CODE_SETTING_UNAVAILABLE)) {
error.setName(msg.getMessage("SETTING.MESSAGE.ERROR", null,null));
error.setValue(msg.getMessage("SETTING.MESSAGE.RESOLUTION", null,null));
return error;
}
StringAttribute map = errorMap.get(code);
if (map == null || map.getName().isEmpty()) {
error.setName(msg.getMessage("DEFAULT.MESSAGE", new Object[] { code }, null));
error.setValue("");
} else {
error.setName(errorMap.get(code).getName());
error.setValue(errorMap.get(code).getValue());
}
return error;
}
}
I tried multiple solution but doesn't work, some time map becomes empty or null.
Any solution works which pass my test case.
I want to test findClientError(String code) and the issue is with errorMap
So, you can use ReflectionUtils.setField method. I made a small example, it is not exactly like your code, but overall you will get the idea.
So here's my class under test. Doing almost exactly like your example. I have hello method just to test and check if it is working or not.
class RateService {
private static Map<String, Object> errorMap = new HashMap<>();
#PostConstruct
public void init () {
this.errorMap = findAllErrors();
}
private Map<String, Object> findAllErrors() {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("a", new Object());
errorMap.put("b", new Object());
errorMap.put("c", new Object());
return errorMap;
}
// a method for demo purposes
public String hello() {
if (errorMap.size() > 0) {
return String.join(",", errorMap.keySet());
} else {
return "Empty";
}
}
}
Here's my test class. The third argument of the setField method is the object that is going to be set in that field. So, you can create a mock, or real object there. I assigned a real object with dummy values. Then tested against that.
class MainTest {
private RateService rateService;
#BeforeEach
void setUp() {
this.rateService = new RateService();
}
private Map<String, Object> exampleErrorObjects() {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("x", new Object());
errorMap.put("y", new Object());
errorMap.put("z", new Object());
return errorMap;
}
#Test
void testHello() {
// given:
ReflectionTestUtils.setField(RateService.class, "errorMap", exampleErrorObjects());
// when:
final String result = this.rateService.hello();
// then:
assertEquals("x,y,z", result);
}
}
I am setting the static field in a test method because you may want your class to be in different states (based on the errorMap field) in each test.
Related
I am facing issues in mocking static method.
Below is my code where I am calling a static method
public class GetAllBatches {
public HttpResponseMessage run(
#HttpTrigger(route = "v1/batches",
name = "request",
methods = {HttpMethod.GET},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<String> request,
final ExecutionContext context){
context.getLogger().info("List batches Called");
String apiResponse ;
String connector = request.getQueryParameters().getOrDefault("connector", "");
try{
BatchesController batchesController = BatchesController.getInstance();
apiResponse = new Gson().toJson(batchesController.getBatches(connector));
}
}
}
BatchesController Class :
public class BatchesController {
Logger log = Logger.getLogger(BatchesController.class.getName());
public static BatchesController getInstance() {
if (batchesController == null) {
batchesController = new BatchesController(BatchDaoFactory.getDao());
}
return batchesController;
}
private static BatchesController batchesController = new BatchesController();
private final BatchDao batchDao;
public BatchesController(BatchDao BatchDao) {
this.batchDao = BatchDao;
}
// Do something
}
And below is the test that I have :
#RunWith(MockitoJUnitRunner.class)
public class GetAllBatchesTest {
#Mock
ExecutionContext context;
#Mock
HttpRequestMessage<String> request;
#Mock
BatchesController batchesController;
#Mock
BatchDao BatchDao;
#InjectMocks
GetAllBatches getAllBatchesMock = new GetAllBatches();
#Before
public void setUp() {
Map<String, String> map = new HashMap<>();
map.put("connector", "");
doReturn(Logger.getGlobal()).when(context).getLogger();
doReturn(map).when(request).getQueryParameters();
try (MockedStatic<BatchesController> utilities = Mockito.mockStatic(BatchesController.class)) {
utilities.when(BatchesController::getInstance).thenReturn(batchesController);
}
doAnswer((Answer<HttpResponseMessage.Builder>) invocationOnMock -> {
HttpStatus status = (HttpStatus) invocationOnMock.getArguments()[0];
return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status);
}).when(request).createResponseBuilder(any(HttpStatus.class));
}
#Test
public void testHttpTriggerJava() {
final HttpResponseMessage ret = getAllBatchesMock.run(request, context);
Assertions.assertEquals(ret.getStatus(), HttpStatus.OK);
}
When I run my test, it throws an error message :
java.lang.ExceptionInInitializerError
BatchesController.getInstance() is not actually returning the mock value.
I am not sure what is going wrong here ?
UPDATE :
I found out that the problem is because I am using Mockito-inline Mockito-inline fails to initiate mock on class but initiates mock only on interfaces
You are using a try-with-resources block to setup a static mock:
try (MockedStatic<BatchesController> utilities = Mockito.mockStatic(BatchesController.class)) {
utilities.when(BatchesController::getInstance).thenReturn(batchesController);
}
Remember that the static mock is only active in scope of the block - after you exit the block the resource is closed.
Thus, you need to:
move the static mock initialization from setup method to the test method
run code under test within the try-with-resources block
Hello everyone i am getting the messages of the users in android studio for that i am refreshing the recyclerview every second but the probem is scrolling when i am scrooling the recyclerview to old messages then its not scrooling becouse of the getting data every second can someone please help me in this
bellow is my activity code
public class Message_User_Activity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
content();
Clicks();
}
public void content()
{
getdata();
refresh(100);
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
toolbar_user_name.setText(name);
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
}
below is my adapter code
public class Message_user_Adapter extends RecyclerView.Adapter<Message_user_Adapter.Message_user_Adapter_View_Holder>
{
List<responsemodel> data;
String mmessage_To;
public Message_user_Adapter(List<responsemodel> data, String message_To) {
this.data = data;
this.mmessage_To = message_To;
}
#NonNull
#Override
public Message_user_Adapter_View_Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_messages_layout,parent,false);
return new Message_user_Adapter_View_Holder(view);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull Message_user_Adapter_View_Holder holder, int position) {
String time = calculateTime(data.get(position).getMessage_Time());
if (data.get(position).getMessage_From().equals(mmessage_To))
{
holder.other_user_message_message_layout.setVisibility(View.VISIBLE);
holder.other_user_message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.GONE);
}
else
{
holder.other_user_message_message_layout.setVisibility(View.GONE);
holder.message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
private String calculateTime(String post_time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
long time = sdf.parse(post_time).getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago+"";
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
public int getItemCount() {
return data.size();
}
public String getdata() {
return mmessage_To.toString();
}
class Message_user_Adapter_View_Holder extends RecyclerView.ViewHolder
{
TextView other_user_message_message_layout;
TextView message_message_layout;
CircleImageView toolbar_user_profile;
public Message_user_Adapter_View_Holder(#NonNull View itemView) {
super(itemView);
other_user_message_message_layout = itemView.findViewById(R.id.other_user_message_message_layout);
message_message_layout = itemView.findViewById(R.id.message_message_layout);
}
}
}
According to my simple information
in your getdata() function. you send new data to Message_user_Adapter of RecyclerView every time you receive data from API or whatever you use ,so the data of adapter every second is change to new data ,so the RecyclerView being recreated every second with new data and the scroll will not work
just try to outage this lines from onResponse to the first of getdata():
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
and in its place add this line to notify the adapter about changed data :
adapter.notifyDatasetChanged()
something like this :
private void getdata() {
toolbar_user_name.setText(name);
String Choice = "Get Messages";
List<responsemodel> data = new ArrayList<>();//this line was change
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);//this line was change
messages_Message_user_RecyclerView.setAdapter(adapter);//this line was change
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
data = response.body();
adapter.notifyDatasetChanged()//this line was added
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
Hi i would like to ask if someone here knows how to have StringRequests on AsyncTask. I have tried it but i get the error on PostExecute.
D/MyDebug: Error on JSON Array org.json.JSONException: End of input at character 0 of
here is my code.
public class MarketsFragment extends Fragment {
private static final String url="http://192.168.1.195/test/test.php";
private static final String STARTING_TEXT ="";
private static String login = null;
private static String debug="MyDebug";
private View rootView;
private ListView lvMarkets;
public static MarketsFragment newInstance(String text)
{
Bundle args = new Bundle();
args.putString(STARTING_TEXT,text);
MarketsFragment marketsHome = new MarketsFragment();
marketsHome.setArguments(args);
return marketsHome;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
rootView = inflater.inflate(R.layout.fragment_markets,container,false);
DBHelper db = new DBHelper(getActivity().getApplicationContext());
final String c_androidid = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
final Cursor rs = db.getID(c_androidid);
rs.moveToFirst();
final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));
AsyncTaskRunner taskRunner = new AsyncTaskRunner();
taskRunner.execute(c_login);
return rootView;
}
private class AsyncTaskRunner extends AsyncTask<String,Integer,String>
{
private ProgressDialog progressDialog;
String requestString="";
String c_login;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Updating Data...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... params)
{
c_login=params[0];
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
JSONArray jArray = null;
try
{
jArray = new JSONArray(response);
requestString=response;
Log.d("MyDebug",response.toString());
}
catch (JSONException e)
{
Log.d("MyDebug","AsyncTask onResponse Error: "+e.toString());
}
}
}, new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
Log.d("MyDebug","Volley Error: "+error.toString());
}
}){
#Override
protected Map<String,String>getParams()
{
Map<String,String>params=new HashMap<String,String>();
params.put("c_login",c_login);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
return requestString;
}
#Override
protected void onPostExecute(String result)
{
try
{
JSONArray jsonArray = new JSONArray(result);
MarketsAdapter marketsAdapter = new MarketsAdapter(getActivity(),jsonArray);
lvMarkets = (ListView)rootView.findViewById(R.id.lvMarkets);
lvMarkets.setAdapter(marketsAdapter);
progressDialog.dismiss();
}
catch (JSONException e)
{
Log.d("MyDebug","Error on JSON Array "+e.toString());
progressDialog.setMessage("Error Updating Data. "+e.toString());
progressDialog.dismiss();
}
}
}
}
I hope you can help me with this one.
Thanks...
First
"End of input at character 0".its because of this you got null response which generated that exception.
if the problem is that you're getting a blank response, you should make sure you get a response from the server before trying to parse it (which is "result" in onPost()).
if the problem is a bad JSON, you should try and validate it. http://jsonlint.com/is a very good to check.
Second
And if Error: com.android.volley.TimeoutError ,
You should set the request's RetryPolicy.
see here..
protected String doInBackground(String... params)
{
..................
..............
int socketTimeout = 30000;//30 seconds - change to what you want
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
queue.add(stringRequest);
return requestString;
}
Third
When you use Volley, there's no need to combine it with AsyncTask. It does the networking stuff on another thread for you.
Thanks..
I have controller method and for it I am making Junit but getting Null pointer error when it calling a service method. I used power mock but still getting Null pointer.
method:
#RequestMapping(method = RequestMethod.GET, value = "/DSR.do")
public ModelAndView displayDataSourceReportPage(HttpServletRequest request,Model model) {
log.debug(" Inside displayDataSourceReportPage method ");
Map<String, Object> map = new HashMap<String, Object>();
try {
request.setAttribute(MENU_SELECTED, LABEL_MENU_SOURCEDATA);
request.setAttribute(SUB_MENU_SELECTED, LABEL_SUBMENU_DSR);
#SuppressWarnings("rawtypes")
List dataSource = dataSourceReportService.listDataSourceReportByCurrentRunInd("C");
map.put("dataSource", dataSource);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return new ModelAndView("DataSourceReport", "model", map);
}
test Method:
#InjectMocks
private DataSourceReportController dataSourceReportController;
#Mock
private DataSourceReportService dataSourceReportServiceImpl;
#InjectMocks
private DataSourceReportDAO dataSourceReportDAO = new DataSourceReportDAOImpl();
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testdisplayDataSourceReportPage() throws Exception {
PowerMockito.mockStatic(DataSourceReport.class);
PowerMockito.mockStatic(HttpServletRequest.class);
PowerMockito.mockStatic(Model.class);
PowerMockito.mockStatic(DataSourceReportService.class);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Model model = Mockito.mock(Model.class);
dataSourceReportServiceImpl = PowerMockito.mock(DataSourceReportService.class);
DataSourceReport dataSourceReport = PowerMockito.mock(DataSourceReport.class);
dataSourceReport.setCurrentRunInd("abc");
dataSourceReport.setActualFileName("Somthing");
dataSourceReport.setFileCountId(3);
dataSourceReport.setFileId(4);
dataSourceReport.setRecCount(3);
List<DataSourceReport> list = new ArrayList<DataSourceReport>();
list.add(dataSourceReport);
String currentRunInd = "currentRunInd";
Object obj =getClass();
PowerMockito.when(dataSourceReportDAO.listDataSourceReportByCurrentRunInd(currentRunInd)).thenReturn(list);
DataSourceReportController ctrl = new DataSourceReportController();
ctrl.displayDataSourceReportPage(request, model);
}
getting Null at "dataSourceReportService.listDataSourceReportByCurrentRunInd("C");"
You need to have this in the test class
PowerMockito.when(dataSourceReportService.listDataSourceReportByCurrentRunInd("C")).thenReturn(list);
before calling
ctrl.displayDataSourceReportPage(request, model);
Thanks # Arthur Zagretdinov
I tried the below code and it worked.
private MockMvc mockMvc;
#Mock
private HttpServletRequest req;
#Mock
private DataSourceReportService dataSourceReportServiceImpl;
#InjectMocks
private DataSourceReportController controller;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Before
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testdisplayDataSourceReportPage() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Model model = Mockito.mock(Model.class);
DataSourceReport dataSourceReport =Mockito.mock(DataSourceReport.class);;
dataSourceReport.setCurrentRunInd("abc");
dataSourceReport.setActualFileName("Somthing");
dataSourceReport.setFileCountId(3);
dataSourceReport.setFileId(4);
dataSourceReport.setRecCount(3);
List<DataSourceReport> list = new ArrayList<DataSourceReport>();
list.add(dataSourceReport);
ModelAndView modelView = controller.displayDataSourceReportPage(request, model);
modelView.addObject(dataSourceReport);
}
I'm very new to Junit.
I'm writing junit for a interceptor.. It contains SessionMap in that.. while calling the interceptor from the test class I'm getting Null pointer exception at Session Map.
Below is my interceptor..
public String intercept(ActionInvocation actionInv) throws Exception {
ActionContext context = actionInv.getInvocationContext();
final HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
String callerAppName = request.getParameter(CustomerPortalConstants.CALLER);
if(callerAppName == null){
//caller name is passed in header in case of OnePortal service request
callerAppName = request.getHeader(CustomerPortalConstants.CALLER);
}
SessionMap<String,Object> sessionMap = ((SessionMap<String,Object>)ActionContext.getContext().getSession());
#SuppressWarnings("unchecked")
Map<String,AccountBean> accountsMap = (Map<String,AccountBean>)sessionMap.get(CustomerPortalConstants.ACCOUNTSMAP);;
if(accountsMap == null) {
accountsMap = new HashMap<String, AccountBean>();
sessionMap.put(CustomerPortalConstants.ACCOUNTSMAP, accountsMap);
}
Im getting error at this location
((SessionMap)ActionContext.getContext().getSession());
This is my Test class..
public class MultiAccountInterceptorTest extends StrutsTestCase implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private Map<String,AccountBean> accountsMap=new HashMap<String, AccountBean>();
Map<String, Object> sessionMap;
private String callerAppName="LMP";
private final HttpServletRequest mockHttpReq = createMock(HttpServletRequest.class);
MultiAccountInterceptor interceptor = new MultiAccountInterceptor();
#SuppressWarnings("unchecked")
#Before
public void setUp() throws Exception {
sessionMap = new HashMap<String, Object>();
}
#SuppressWarnings("unchecked")
#Test
public void testIntercept() throws Exception
{
MultiAccountInterceptor mockInterceptor = PowerMock.createNicePartialMockForAllMethodsExcept(MultiAccountInterceptor.class, "intercept");
final ActionInvocation mockInvocation = createMock(ActionInvocation.class);
final ActionContext mockContext = createMock(ActionContext.class);
expect(mockInvocation.getInvocationContext()).andReturn(mockContext);
System.out.println(mockContext);
expect( (HttpServletRequest)mockContext.get(ServletActionContext.HTTP_REQUEST)).andReturn(mockHttpReq);
System.out.println(mockHttpReq);
expect(mockHttpReq.getParameter(CustomerPortalConstants.CALLER)).andReturn(callerAppName);
System.out.println("Caller app name is"+ callerAppName);
System.out.println(sessionMap);
sessionMap.put(CustomerPortalConstants.ACCOUNTSMAP, accountsMap);
System.out.println(sessionMap);
replayAll();
mockInterceptor.intercept(mockInvocation);
}
#Override
public void setSession(Map<String, Object> sessionMap) {
this.sessionMap=sessionMap;
}
}
Can anyone provide me a solution for this problem..
Thanks in advance..