JUNIT : how to call static methods through mock objects.
Hi,
I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
Can any one suggest me that how can I call static methods through mock objects.
The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
instead of :
public class Helper() {
public static void getSomeHelp();
public class MockHelper() {
public static void getSomeHelp();
}do :
public class ClassUnderTest {
private Helper helper;
public void methodUnderTest() { // unchanged
helper.getSomeHelp();
public interface Helper {
public void getSomeHelp();
public class HelperImpl implements Helper {
public void getSomeHelp() {
// actual implementation
public class MockHelper implements Helper {
public void getSomeHelp() {
// mock implementation
}
Similar Messages
-
Reflection: how to call static method?
You can call an instance method for an object via
Method method = myClass.getDeclaredMethod(mName, mTypes);
Object value = method.invoke(instance, mValues);But how do you call a static method (that is perhaps in an abstract class)? Is it save to have the instance variable null?Is it save [sic] to have the instance variablenull?Please refrain to mock at that, Peter. Even the
English often confuse "loose" and "lose", don't be
that critical to foreigners. :-)Is there something wrong? I just serach via google:
"is it save to" ... results: 800 ...
Okay, "is it safe to" : 636.000 ... :-) -
How to call paint() method during creating object
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
class SomeShape extends JPanel {
protected static float width;
protected BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
class Oval extends SomeShape {
Oval(float width) {
this.width = width;
line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
repaint();
public void paint(Graphics g) {
Graphics2D pen = (Graphics2D)g;
int i = 10;
super.paint(g);
g.setColor(Color.blue);
g.drawOval(90, 0+i, 90, 90);
System.out.println("paint()");
public class FinalVersionFactory {
JFrame f = new JFrame();
Container cp = f.getContentPane();
float width = 0;
SomeShape getShape() {
return new Oval(width++); //I want to paint this oval when I call getShape() method
public FinalVersionFactory() {
f.setSize(400, 400);
// cp.add(new Oval()); without adding
cp.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
getShape();
f.setVisible(true);
public static void main(String[] args) { new FinalVersionFactory(); }
}I need help. When I cliked on the JFrame nothing happened. I want to call paint() method and paint Oval when I create new Oval() object in getShape(). Can you correct my mistakes? I tried everything...Thank you.import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
class SomeShape extends JPanel {
protected static float width;
protected static BasicStroke line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
class Oval extends SomeShape {
static int x, y;
Oval(float width, int x, int y) {
this.width = width;
this.x = x;
this.y = y;
line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
public void paint(Graphics g) {
Graphics2D pen = (Graphics2D)g;
g.setColor(Color.blue);
pen.setStroke(line);
g.drawOval(x, y, 90, 90);
System.out.println("Oval.paint()"+"x="+x+"y="+y);
class Rect extends SomeShape {
static int x, y;
Rect(float width, int x, int y) {
this.width = width;
this.x = x;
this.y = y;
line = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.CAP_ROUND);
public void paint(Graphics g) {
Graphics2D pen = (Graphics2D)g;
g.setColor(new Color(250, 20, 200, 255));
pen.setStroke(line);
g.drawRect(x, y, 80, 80);
System.out.println("Rect.paint()"+"x="+x+"y="+y);
public class FinalVersionFactory extends JFrame {
Container cp = getContentPane();
float width = 0;
int x = 0;
int y = 0;
boolean rect = false;
SomeShape getShape() {
SomeShape s;
if(rect) {
s = new Rect(width, x, y);
System.out.println("boolean="+rect);
} else {
s = new Oval(width++, x, y);
System.out.println("boolean="+rect);
System.out.println("!!!"+s); //print Oval or Rect OK
return s; //return Oval or Rect OK
public FinalVersionFactory() {
setSize(400, 400);
SomeShape shape = getShape();
cp.add(shape); //First object which is add to Container(Oval or Rect), returned by getShape() method
//will be paint all the time. Why? Whats wrong?
cp.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
x = e.getX();
y = e.getY();
rect = !rect;
getShape();
cp.repaint(); //getShape() return Oval or Rect object
//but repaint() woks only for object which was added(line 67) as first
setVisible(true);
public static void main(String[] args) { new FinalVersionFactory(); }
}I almost finish my program but I have last problem. I explained it in comment. Please look at it and correct my mistakes. I will be very greatful!!!
PS: Do you thing that this program is good example of adoption Factory Pattern? -
How to call the Jsp through BPM Obejct
Hi,
I have gone through the some topic, how to call the Jsp through BPM Object.
I have followed step below,
1. I have create the sample jsp page
2. Import into BPM studio under webroot\custom Jsp
3. Created the screenflow and added the "Interactive Component call" object
4. Right Click the Object and selected Maintask and Implementation type as "BPM Object Interactive Call"
5. Selected the use JSP presentation object option and when i click ok its showing "BPM instance object must be selected"
But when i select the Instance Variable tab, its not showing anything.
Can any one help me how to call the Jsp in screenflow with step by step procedure, that would be very greate help for me.
Regards,
Anandh PHi,
You are running a jsp report through rwservlet. In this case paper layout will be displayed. You have to deploy your jsp as web report to get the web layout. Please refer to the doc below, which describes how to deploy the web report.
http://download-uk.oracle.com/docs/html/B10314_01/pbr_run.htm#1011901
To run the jsp report, URL may look like
http://www.wwt.com/reports/<jsp name>?<parameter list>
Hope this helps
Vinayak -
How to call a method of a zclass into web dynpro application
How to call a method of a zclass into web dynpro application
Hi,
if the method is of type static then u can access it directly as below.
call method class_name=>method_name
If the method is instance method then U need to create the object of that class. then through this object u can access the method.
CALL METHOD Obj_name->method_name -
Export Internal table by calling static method
Hi friends,
Can u please tell me how to get internal table in export parameter by calling static method.
OR can u tell me how to declare internal table in method parameter.
Thanks in advanceRaja's method will work for all tables irrespective of the structure and is the best possible approach. However, if your requirement is simple and you do not have to deal with a lot many tables,
1. Create a Type-Pool, suppose ztypl
2. Within the type pool, declare a Structure type,
TYPES: BEGIN OF ztypl_struct1,
"Place your fields here
END OF ztypl_strict1,
"Create a table of type ztypl_struct1 here
ztypl_table1 TYPE TABLE OF ztypl_struct1.
Use "ZTYPL_TABLE1" as the "Associated type" in your method's Parameter definition in SE24.
eg.
IT_TABLE TYPE ZTYPL_TABLE1
If you are writing your class in an include,
METHODS my_method1
IMPORTING
it_table1 TYPE ztypl_table1.
Do remember to include
TYPE-POOLS: ztypl.
in your class's Constructor / Include program.
Please award points if helpful.
Regards,
Ryan
Message was edited by:
Ryan Cannel -
How to call main method in one class from another class
Suppose i have a code like this
class Demo
public static void main(String args[])
System.out.println("We are in First class");
class Demo1
public static void main(String args[])
System.out.println("We are in second class");
In the above program how to call main method in demo calss from Demo1 class......???????No, i dont know how to call other than main methods from other classes
And one more doubt i have i.e. Like in C can we see the execution of the program like how the code is being compiled step by step and how the value of the variable changes from step to step like(Add Watch)......... -
How to call a method of another class ?
Hello,
I�d like to know how to call a method of another class. I have to classes (class 1 and class 2), class 1 instantiates an object of class 2 and executes the rest of the method. Later, class 1 has to call a method of class 2, sending a message to do something in the object... Does anybody know how to do that ? Do I have to use interface ? Could you please help me ?
Thanks.
Bruno.Hi Schiller,
The codes are the following:
COMECO
import javax.swing.UIManager;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
//Main method
class comeco {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch(Exception e) {
AGORA testeagora=new AGORA();
// Code for socket
int port;
ServerSocket server_socket;
BufferedReader input;
try {
port = Integer.parseInt(args[0]);
catch (Exception e) {
System.out.println("comeco ---> port = 1500 (default)");
port = 1500;
try {
server_socket = new ServerSocket(port);
System.out.println("comeco ---> Server waiting for client on port " +
server_socket.getLocalPort());
// server infinite loop
while(true) {
Socket socket = server_socket.accept();
System.out.println("comeco ---> New connection accepted " +
socket.getInetAddress() +
":" + socket.getPort());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// print received data
try {
while(true) {
String message = input.readLine();
if (message==null) break;
System.out.println("comeco ---> " + message);
testeagora.teste(message);
catch (IOException e) {
System.out.println(e);
// connection closed by client
try {
socket.close();
System.out.println("Connection closed by client");
catch (IOException e) {
System.out.println(e);
catch (IOException e) {
System.out.println(e);
AGORA
import javax.swing.UIManager;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.net.*;
//public class AGORA {
public class AGORA {
boolean packFrame = false;
//Construct the application
public AGORA() {
try {
Main frame = new Main();
System.out.println("agora ---> Criou o frame");
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame)
frame.pack();
else
frame.validate();
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height)
frameSize.height = screenSize.height;
if (frameSize.width > screenSize.width)
frameSize.width = screenSize.width;
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
catch(Exception e)
{ System.out.println("agora ---> " +e);
// Tem que criar a THREAD e ver se funciona
public void remontar (final String msg) {
try {
System.out.println("agora ---> Passou pelo Runnable");
System.out.println("agora --> Mensagem que veio do comeco para agora: "+ msg);
Main.acao(msg);
catch(Exception x) {
x.printStackTrace();
MAIN
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;
import javax.swing.border.*;
import java.net.*;
import java.io.*;
public class Main extends JFrame {
// ALL THE CODE OF THE INTERFACE
//Construct the frame
public Main() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
public void acao() {
// C�digo para mudar a interface
Runnable setTextRun=new Runnable() {
public void run() {
try {
System.out.println("main ---> Passou pelo Runnable");
TStatus.setText("main ---> Funcionou");
catch(Exception x) {
x.printStackTrace();
System.out.println("main ---> About to invokelater");
SwingUtilities.invokeLater(setTextRun);
System.out.println("main ---> Back from invokelater");
// Aqui vai entrar o m�todo para ouvir as portas sockets.
// Ele deve ouvir e caso haja alguma nova mensagem, trat�-la para
// alterar as vari�veis e redesenhar os pain�is
// Al�m disso, o bot�o de refresh deve aparecer ativo em vermelho
//Component initialization
private void jbInit() throws Exception {
// Initialize the interface
//Setting | Host action performed
public void SetHost_actionPerformed(ActionEvent e) {
int port;
ServerSocket server_socket;
BufferedReader input;
System.out.println("main ---> port = 1500 (default)");
port = 1500;
try {
server_socket = new ServerSocket(port);
System.out.println("main ---> Server waiting for client on port " +
server_socket.getLocalPort());
// server infinite loop
while(true) {
Socket socket = server_socket.accept();
System.out.println("main ---> New connection accepted " +
socket.getInetAddress() +
":" + socket.getPort());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String espaco=new String(": ");
JLabel teste2=new JLabel(new ImageIcon("host.gif"));
PHost.add(teste2);
System.out.println("main ---> Adicionou host na interface");
repaint();
System.out.println("main ---> Redesenhou a interface");
setVisible(true);
// print received data
try {
while(true) {
String message = input.readLine();
if (message==null) break;
System.out.println("main ---> " + message);
catch (IOException e2) {
System.out.println(e2);
// connection closed by client
try {
socket.close();
System.out.println("main ---> Connection closed by client");
catch (IOException e3) {
System.out.println(e3);
catch (IOException e1) {
System.out.println(e1);
public void OutHost_actionPerformed(ActionEvent e) {
repaint();
setVisible(true);
//Help | About action performed
public void helpAbout_actionPerformed(ActionEvent e) {
Main_AboutBox dlg = new Main_AboutBox(this);
Dimension dlgSize = dlg.getPreferredSize();
Dimension frmSize = getSize();
Point loc = getLocation();
dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
dlg.setModal(true);
dlg.show();
//Overridden so we can exit on System Close
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if(e.getID() == WindowEvent.WINDOW_CLOSING) {
fileExit_actionPerformed(null);
public void result(final String msg) {
// C�digo para mudar a interface
Runnable setTextRun=new Runnable() {
public void run() {
try {
System.out.println("main ---> Chamou o m�todo result para mudar a interface");
System.out.println("main --> Mensagem que veio do agora para main: "+ msg);
TStatus.setText(msg);
catch(Exception x) {
x.printStackTrace();
System.out.println("main --> About to invokelater");
SwingUtilities.invokeLater(setTextRun);
System.out.println("main --> Back from invokelater");
[]�s. -
How to call a method in private section of a class in the public section
Hi Everybody,
i have written a method(meth1) in the private section of a class(C1).
it is as follows
class C1 definition.
private section.
methods: meth1 importing im_dt1 like tp1
im_dt2 like tp2
im_dt3 like tp3
im_dt4 like tp4
returning value(re_dt1) like tp5.
endclass.
i have the final data that has to be displayed in internal table re_dt1.
now my question is how to call this method present in private section into public section and display the data present in re_dt1.
Thanks,
learning.abap.Hi,
what you need is one public method being called at start-of-selection. Within this the private methods have to be called.
The question is, why has the method for reading the database tables to be private? If you have only one private method reading all database tables the public method being called at start-of-selection will only consist of a call-method statement.
This seems to be one call to much.
The logic for reading the different database tables is hidden inside the class anyway.
Is there any further logic reading the different database tables?
Have always all table to be read? If not another approach would be one private method for each database table being called by a public method deciding which table has to be read:
public section.
methods get_data returning value(re_Dt1).
private section.
methods:
get_table_a returning value(im_dt1),
get_table_b returning value(im_dt2),
get_table_c returning value(im_dt3),
get_table_d returning value(im_dt4),
combine_data importing im_dt1
im_dt2
im_dt3
im_dt4
returning value(re_dt1).
*- implementation of public method:
method get_data.
data: lt_dt1 ...
lt_dt2,
lt_dt3,
lt_dt4.
* here decide which tables have to be read:
lt_dt1 = get_table_a( ).
lt_dt2 = get_table_b( ).
lt_dt3 = get_table_c( ).
lt_dt4 = get_table_d( ).
re_dt1 = combine_data( i_dt1 = lt_dt1
i_dt2 = lt_dt2
i_dt3 = lt_dt3
i_dt4 = lt_dt4 ).
endmethod.
*- implementation of private methods
method get_table_a.
endmethod.
method get_table_b.
endmethod.
method get_table_c.
endmethod.
method get_table_d.
endmethod.
method combine_data.
endmethod.
Regards
Dirk -
How to call a Method in a Program?
Hello,
I am very new to the ABAP world. I have been given a task to call a method if_hrbas_plain_infotype_access~read_single from the class CL_HRBAS_PLAIN_INFOTYPE_ACCESS in a program to see if we can use it to display some employee information. I don't know how to call a method in a program. Can somebody please provide me some pseudo code or instructions?
Thanks.Hi Shan,
here is the code to call a method. while calling the method Instance as 'r_info' which is the type reference to class as specified.
pass the values to exporting parameters plvar,otype,objid...etc according to the requirement
infotypes: 0002. " creates an internal table p0002.
data:
r_info type ref to CL_HRBAS_PLAIN_INFOTYPE_ACCESS.
TRY.
CALL METHOD r_info->if_hrbas_plain_infotype_access~read
EXPORTING
plvar =
otype =
objid =
istat =
infty =
* SUBTY =
begda =
endda =
no_auth_check = 'X'
message_handler =
IMPORTING
PNNNN_TAB = P0002
* HRTNNNN_TAB =
* IS_OK =
CATCH CX_HRBAS_VIOLATED_ASSERTION .
ENDTRY.
LOOP AT P0002.
WRITE:/
P0002-VORNA,
P0002-NCHMC,
P0002-NACHN.
ENDLOOP.
Regards -
How to call a method from a separate class using IBAction
I can't work out how to call a method form an external class with IBAction.
//This Works 1
-(void)addCard:(MyiCards *)card{
[card insertNewCardIntoDatabase];
//This works 2
-(IBAction) addNewCard:(id)sender{
//stuff -- I want to call [card insertNewCardIntoDatabase];
I have tried tons of stuff here, but nothing is working. When i build this I get no errors or warnings, but trying to call the method in anyway other that what is there, i get errors.Can you explain more about what you are trying to do? IBAction is just a 'hint' to Interface Builder. It's just a void method return. And it's unclear what method is where from your code snippet below. is addNewCard: in another class? And if so, does it have a reference to the 'card' object you are sending the 'insertNewCardIntoDatabase' message? Some more details would help.
Cheers,
George -
How to call java function through Web Service
Hello Experts,
I want to call a method through Java Web Service in my abap code. Is it possible ? If so, plz guide me.
Requirement: In SD module user enters the PAN, on after entering PAN in want to validate it on NSDL. For that a Web Service has already been deployed on a Web Server. and that the deployed Web Service I want to call in abap code.Hi,
check this link
Re: Call to WS from one backend to other backend
regards
afzal -
How to call java fanction through Web Service
Hello Experts,
I want to call a method through Java Web Service in my abap code. Is it possible ? If so, plz guide me.
Requirement: In SD module user enters the PAN, on after entering PAN in want to validate it on NSDL. For that a Web Service has already been deployed on a Web Server. and that the deployed Web Service I want to call in abap code.Hi,
check this link
Re: Call to WS from one backend to other backend
regards
afzal -
How to call a method defined in AM when I select any value in LOV
Lets say there is a LOV. The scenario is as soon as I select any value in LOV, a method needs to be called which I have written in the AM. And the output of the method is displayed in a output text box.
I am not able to understand how to call a method when the user selects any value in LOV.
This is wht I did. I had created the binding for the method. Changed the autosubmit property of the LOV to True, and in the properties of the output box, in the partial submit trigger property, passed the ID of the LOV. But I didnt get any place where I need to call the method. I am also not able to drop an action listener on the LOVHi,
+"its showing an error(underlined in orange)."+
Any reason you don't share this error with us? Anyway, here is how it goes
1. LOV, set autosubmit="true" and configure a value change listener
2. Expose the AM method as a method binding in the PageDef file
3. In the value change listener:
BindingContext bctx = BindingContxt().getCurrent();
BindingContainer bindings = bctx.getCurrentBindingsEntry();
OperationBinding method = (OperationBinding) bindings.get("name of method binding in PageDef");
method.getParamsMap().put("argument name1", value1);
method.getParamsMap().put("argument name2", value2);
Object retVal = method.execute();
if(!method.getErrors().isEmpty()){
//handle errors
else{
//write retVal to the managed bean variable that is referenced by the outputText value property
//PPR output text component
ADFFacesContext.getCurrentInstance().addPartialTarget(outputTextRef);
}Note that you may have to set clientComponent = "true" on the output text component
Frank -
How to call a method in the servlet from an applet
I want to get the data for the applet from the servlet.
How to call a method that exits in the servlet from the applet? I want to use http protocol to do this.
Any suggestions? Please help.
thanksNow that Web Services is around, I'd look at possibly implement a Web Service call in your applet, which can then be given back any object(s) on return. Set up your server side to handle Web Service calls. In this way, you can break the applet out into an application should you want to (with very little work) and it will still function the same
Maybe you are looking for
-
I am new to Java and am trying to learn how to use and understand the nuances involved in using the Switch statment. I am trying to write an application that will calculate grades for a student. I can use the If Then Else Control structure for this (
-
I have recently reinstalled itunes on to my laptop. I have tv shows in my library which i downloaded from itunes but when I try and sync them to my ipad it doesn't show them in the sync page. can anyone help ?
-
4/22/2015 - Beta - Flash Player 18.0.0.95
The latest Flash Player 18 beta builds are now available. Beta builds can be downloaded from labs.adobe.com. New Features for Flash Player 18: Improve Flash Player Install Process We have had consistent feedback from our customers that they prefer n
-
Can I add a wifi network that is out of range - ipad 3 latest ios
We bought an iPad for a relative for Christmas. We expect that it will be used lightly, mostly emails and games, as the user is not very "technically minded". The iPad links up fine to our wifi but before she returns home I wanted to set up her iPad
-
Enabling autoconfig on DB tier After upgrade from 9i to 10g
Environment: 11.5.10.2 Number of Nodes: 2 Node1: Db & Conc Manager Node2: Admin, Forms,Reports, web I have upgraded the Apps 11i database 9.2.0.6 to 10.2.0.4 Now I have to enable autoconfig on new DB home 1) I have generated appsutil.zip on node2 and