how to test a thread using powermock? - java

There's a piece of code im trying to test,
which goes something like this:
class Foo {
//do some operations
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//some piece of code
}
}
}
So how do i test the code within the run function.
I am using powermock,
The thread is started in another class so i should not invoke it there right??
im still a beginner.

The code in the Runnable's run() method will be invoked on the Event Dispatch Thread. Usually only GUI updates should be performed on this thread. Using mock objects to test the GUI is not a good idea.

Depends on what you're trying to test.
If you're testing the behavior of Foo - don't worry about the concurrency. Just make your calls to Foo and assert that the result obtained matches your expectations. Just org.junit.Assert will be enough.
If you're testing what this Runnable will actually do, you need to break dependencies first. Now your class Foo depends on some Runnable, which is instantiated and called internally. Convert it to an argument of Foo:
class Foo {
private Runnable runnable;
public Foo(Runnable rnbl) {
this.runnable = rnbl;
}
// somewhere later in the class
SwingUtilities.invokeLater(this.runnable);
}
Now you can mock this Runnable with, say, Mockito and test (in your unit test):
Runnable mock = Mockito.mock(Runnable.class);
Foo foo = new Foo(mock);
foo.doSomething();
Mockito.verify(mock).run(); // verify that it was called
This is how you turn your multi-thread application into single-thread for testing only.

As i understand the main problem is asynchrony. Test checks a result before we'll get result from invokeLater() block. So we need to wait until EDT run our code and after that check. We can do it via invokeAndWait method with empty runnable block. Example Foo class:
import javax.swing.SwingUtilities;
public class Foo {
private String myLine;
public void executeInEDT(final String line) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
myLine = line;
}
});
}
public String getLine() {
return myLine;
}
}
and test method:
#Test
public void testInvokeLater() throws InterruptedException, InvocationTargetException {
String testLine = "Test line";
Foo foo = new Foo();
foo.executeInEDT(testLine);
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
// Just for sync
}
});
assertEquals(testLine, foo.getLine());
// And more asserts
}
UPD: Found some more information in Netbeans test patterns:
As the queue of runnables is FIFO, the runnable is scheduled at the
end after all tasks posted by the application and when it is finally
executed one can be sure that all delayed tasks of the application in
the AWT event queue are over as well. See DataEditorSupportTest.java
for an example of a test that needs to wait while the application code
finishes some actions posted to the AWT event thread.

Related

How to do Unit Testing for asynchronous calls?

I want to do Unit Tests for asynchronous methods in android. The result needs to be a "notified by observer's callback". Have a look at the below example. How can I write a unit test case for doSomething() method?
public interface IFooObserver {
void onResult(String result);
}
public class Foo {
private IFooObserver mObserver;
public Foo(IFooObserver observer) {
mObserver = observer;
}
public void doSomething() {
new Thread(new Runnable() {
#Override
public void run() {
// do something..
mObserver.onResult("hello, world!");
}
}).start();
}
}
Simply: don't use "bare metal" threads.
Use ExecutorServices instead - because that allows you to use dependency injection to turn your multi-threaded code into a single-threaded thing for testing - using a Same Thread Executor Service.
Example:
class Whatever {
private final ExecutorService service;
Whatever() { this ( Executors.newSingleThreadExecutor() ); }
Whatever(ExecutorService service) { this.service = service; }
void foo() {
service.submit ( ... whatever
The point is: when you are using a thread directly, you have no control whatsoever there. Most likely, that will lead to test cases that need complicated signaling, or worse: rely on calling sleep() here or there. And that is always bad - it increases the execution time of your tests; or, worse, you get the timing wrong; and occasionally your tests fail during regression. Because of different load on your test system; and threads showing different runtime characteristics.
So, long story short: if possible, avoid using threads directly; instead use the aforementioned concept to simply avoid multiple threads for testing.

Java new Thread using this - Any reason if it is good / bad?

Just a quick question look at the code below, is there any reason why wouldn't do this or is it fine?
public class MyClass implements Runnable, MyClassInterface {
Thread threader;
void start() {
threader = new Thread(this);
threader.start();
}
#Override
public void run() {
Thread current = Thread.getCurrentThread();
while (threader = current) {
..
}
}
}
The original logic was not to expose that fact it runs in a separate thread to the caller
who creates a "MyClass" but then there are doubts if that is a good thing or bad.
Can anyone see any good reason not to do it or is it acceptable. It can be expected that MyClass.start() maybe called a few times.
EDIT: Updated the code to show it is implementing Runnable and one other interface, the interface is used by client code, the actual implementation may run in a separate thread, same thread or any other way. The idea was to abstract that away from the client, as the client is simply an object that "MyClass" will notify and is not aware (currently) of the Runnable interface it implements.
Perhaps that abstraction is not needed and client should have more control?
EDIT: The start() was simply to tell the object it is ready to start receiving notifications rather than start a thread.
Have a look at this: http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
In my opinion, it is a bad design, because you are breaking encapsulation by implementing an interface (Runnable) and by providing a public method (run) that are of no use of the consumer of the class.
You can start a thread from the start method without inhering from Runnable:
public class MyClass {
private Thread thread;
public void start() {
thread = new Thread(this::doWork); // Java 8 method reference
thread.start();
}
private void doWork() {
// ...
}
}
If you can't use method references from Java 8, replace this::doWork with:
new Runnable() { public void run() { doWork(); } }

Other method in thread executing before run method in java

In my program I am calling the thread to do some job but the other method of thread class executes before the run method.
public class Verify extends JFrame implements Runnable
{
long Local_cid;
String local_path;
static boolean isIntialised=false;
JProgressBar bar;
final static ArrayList<Long> ContactList=new ArrayList<>();
final static ArrayList<Long> Scanned=new ArrayList<>();
static boolean flag=true;
static boolean Duplicate_flag=true;
boolean[] flags=new boolean[6];
public Verify(long ID,String path)
{
Local_cid=ID;
local_path=path;
}
public boolean[] Return_Flag()
{
System.err.println("Verify Id");
return flags;
}
public void dispose_Frame()
{
System.err.println("Executing First");
dispose();
}
#Override
public void run()
{
System.err.println("This should Executed First");
}
}
When I call this thread via start call the output is as follows:
Verify Id
Executing First
This should Executed First
You should follow the Java coding standard style guides, it will make it much easier for people to read.
There is nothing in the code you have posted that calls Return_Flag() so you must be calling it somewhere else - probably from the code that creates the thread in the first place.
Run is only called once the thread is started, and other threads are still running at the same time and can call whatever methods they like in whatever order they like...
I'm 100% sure that you are calling those methods somewhere in your code before actually starting the thread. Just look more careful and you will find it.

Easy way to call method in new thread

I'm writing small app and now I discovered a problem.
I need to call one(later maybe two) method (this method loads something and returns the result) without lagging in window of app.
I found classes like Executor or Callable, but I don't understand how to work with those ones.
Can you please post any solution, which helps me?
Thanks for all advices.
Edit: The method MUST return the result. This result depends on parametrs.
Something like this:
public static HtmlPage getPage(String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
return webClient.getPage(page);
}
This method works about 8-10 seconds. After execute this method, thread can be stopped. But I need to call the methods every 2 minutes.
Edit: I edited code with this:
public static HtmlPage getPage(final String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
Thread thread = new Thread() {
public void run() {
try {
loadedPage = webClient.getPage(page);
} catch (FailingHttpStatusCodeException | IOException e) {
e.printStackTrace();
}
}
};
thread.start();
try {
return loadedPage;
} catch (Exception e) {
return null;
}
}
With this code I get error again (even if I put return null out of catch block).
Since Java 8 you can use shorter form:
new Thread(() -> {
// Insert some method call here.
}).start();
Update:
Also, you could use method reference:
class Example {
public static void main(String[] args){
new Thread(Example::someMethod).start();
}
public static void someMethod(){
// Insert some code here
}
}
You are able to use it when your argument list is the same as in required #FunctionalInterface, e.g. Runnable or Callable.
Update 2:
I strongly recommend utilizing java.util.concurrent.Executors#newSingleThreadExecutor() for executing fire-and-forget tasks.
Example:
Executors
.newSingleThreadExecutor()
.submit(Example::someMethod);
See more: Platform.runLater and Task in JavaFX, Method References.
Firstly, I would recommend looking at the Java Thread Documentation.
With a Thread, you can pass in an interface type called a Runnable. The documentation can be found here. A runnable is an object that has a run method. When you start a thread, it will call whatever code is in the run method of this runnable object. For example:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Insert some method call here.
}
});
Now, what this means is when you call t.start(), it will run whatever code you need it to without lagging the main thread. This is called an Asynchronous method call, which means that it runs in parallel to any other thread you have open, like your main thread. :)
In Java 8 if there is no parameters required you can use:
new Thread(MyClass::doWork).start();
Or in case of parameters:
new Thread(() -> doWork(someParam))

How do I test this method's expected behavior in Java: it spawn a thread, and throws an exception under certain conditions

Suppose that I have a method which spawns a new thread and do some work. Under certain conditions, the newly spawn thread would throw a certain type of exception, which terminates the entire process. I would like to write JUnit tests to verify this behavior. Is there a way to do it?
The method is:
private void foo() {
new Thread() {
#Override void run() {
throw new CertainException("exception messages");
}
}.start();
}
In test (conceptually):
public testExceptionThrownFromNewThread() throws Exception {
try {
foo();
Thread.sleep(5000); // wait for the exception to be thrown
fail();
} catch (CertainException e) {
assertEquals(e.message, "exception messages");
}
}
This test doesn't work because the exception spawn from the other thread cannot be caught.
If you want to test just the code inside of the run() method, refactor it ouf of the foo() method (probably into a Runnable) and test it separately without running it from a thread.
private void foo() {
new Thread(new MyRunnable()).start();
}
public class MyRunnable implements Runnable {
public void run() {
....
}
}
Now you can instantiate a MyRunnable object and call the run() method from your test without needing to start a thread.
EDIT
Testing of the thread creation could be done by using a ThreadFactory Mock. (as Jon Skeet pointed out).
You could overwrite the default UncaughtExceptionHandler for Threads. It gets called whenever a Thread throws an exception. In this handler, you can check whether the expected exception is equal to the thrown exception and e.g. test for messages or count the occurences of the exception. By using a CountDownLatch, you can also check whether the exceptions are thrown in time and how many of them you expect.
This works even if you do not have access to the Thread created by the class under test. If you have access to it though, there is certainly an easier approach, e.g. refactoring the class under test and introduce an Exception Listener or alike. Make the class under test better testable also improves the design, e.g. by removing the dependency on Threads and directly test the body of the run() method which you could externalize.
public class ThreadExceptionTest {
private void foo() {
new Thread(new Runnable() {
#Override
public void run() {
throw new RuntimeException("exception messages");
}
}).start();
}
#Test
public void testFoo() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final RuntimeException expectedException = new RuntimeException("exception messages");
UncaughtExceptionHandler eh = new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
if (e.getMessage().equals(expectedException.getMessage()))
latch.countDown();
}
};
Thread.setDefaultUncaughtExceptionHandler(eh);
foo();
assertTrue(latch.await(100,TimeUnit.MILLISECONDS));
}
}
Well, unit tests are supposed to verify results of method calls, not implementation details.
In your library, if thread terminates, how does it affect library user? Maybe computations won't be finished and end results won't be recored in database? Then check database. Maybe thread will stop doing some periodic tasks (like cleanup)? Then check whether cleanup is still being done.
And if exception thrown won't affect user in any way, then there's nothing to check. Because whether exception is thrown or not is just an implementation details (user will never see it).
One option is to make the capability to start a thread a dependency - which you can specify using the existing ThreadFactory interface. Then in your unit test you can provide a specialist ThreadFactory which wraps the given Runnable in order to record exceptions etc.
You'll be able to test that:
The ThreadFactory was used
The thread was started
The operation threw an exception

Categories