How to test class which implements Runnable with Junit
Separate the concerns : the Runnable
and the logic associated.
It will make in addition your code mode testable.
You could extract sendRequest()
in a Foo
class that the Processor
class depends on.
Then you have just to mock this Foo
class in your test and verify that the sendRequest()
method was invoked.
For example :
public Processor implements Runnable{
private Foo foo;
public Processor(Foo foo){
this.foo = foo;
}
public void run() {
while (true) {
//some code
foo.sendRequest(object);
}
}
}
And the test :
@Mock
Foo fooMock;
@Test
public void run() {
Processor processor = new Processor(fooMock);
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(processor);
executor.awaitTermination(someTime, TimeUnit.SECONDS);
Mockito.verify(fooMock).sendRequest(...);
}
How to unit test a class that implements Runnable
I guess you only want to test if the run()
method does the right thing. At the moment you also test the ServiceExecutor
.
If you just want to write a unit test you should call the run
method in your test.
public class ExampleThreadTest {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionForInvalidNumber() {
ExampleThread exThread = new ExampleThread(-1);
exThread.run();
}
}
How do I Unit Test Runnable Class?
you can try to test like this
public class TestMultiThread {
@Test
public void testThread(){
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new ReportSenderRunnable());
System.out.println("started Report Sender Job");
}
}
create junit test for runnable class
To test the runnable running in a separate thread, the JUnit test should (1) construct the runnable, (2) start a thread constructed on the runnable, (3) queue a few entries, (4) wait for a short period, (5) call stop(), and (6) check that all entries got processed.
In this case, your code will fail the test since your run() method does not have a loop and thus will only process the first entry. It also doesn't have any code for processing the entry and doesn't compile yet.
In addition to the JUnit test, you need to do a careful code inspection for concurrency issues. For example, processEntries needs to be volatile.
Junit for runnable class and Queue
In your test
method, you created a new queue that has nothing to do with your m_Processor
instance; it goes unused entirely. You need to change your code so you can get the PersistentQueue
instance contained inside your m_Processor
instance. Assuming you have a getter method called getPersistentQueue
inside Processor
, then you can use the following:
@Test
public void test() {
m_Processor.addToQueue(event);
assertEquals(1, m_Processor.getPersistentQueue().size());
}
Unit test for Runnable with Mockito
Pass a mock Handler
to the constructor of TestClass
.
Then use Mockito.verify()
to assert that callHandler()
method was called.
Involving concurrency
You can stub an answer that counts down on a CountDownLatch
to make the test wait for the handler to be hit. Waiting will involve setting a reasonable timeout, which can be tricky, you don't want it too high, or failure will make the test run much longer, and not too low so that you don't get false positives.
Handler handler = mock(Handler.class);
CountDownLatch finished = new CountDownLatch(1);
doAnswer(invocation -> {
finished.countDown();
return null;
}).when(handler).callHandler();
TestClass testClass = new TestClass(executor, handler);
testClass.doSomething("thisThing");
boolean ended = finished.await(10, TimeUnit.SECONDS);
assertThat(ended).isTrue();
verify(handler).callHandler();
Bypassing concurrency
If you're only trying to determine whether the handler is invoked you can use an Executor
that executes on the same thread. This will make for a more stable test.
Handler handler = mock(Handler.class);
Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
TestClass testClass = new TestClass(executor, handler);
testClass.doSomething("thisThing");
verify(handler).callHandler();
How to mock run() method of Runnable subclass with required parameters
After looking into multiple posts, I finally got the solution.
Because of the @RequiredArgsConstructor
paramater creating an object of Event class will not happen through no arguement constructor.
Code inside unit test case class :
@Mock Person person;
@Mock Student student;
@Injectmocks Event event;
@Test
private void testfunction(){
Event event = new Event(person,student);
event.run();
//mockito.verify()...
}
How to write Junit test cases for a Thread class
Don't extend Thread. Implement Runnable. Test the run() method the same way you would test any "ordinary" method.
The obvious benefit of this approach is that you don't need to deal with concurrency at all.
Related Topics
Select the Letters After - in a String
Using Nested While Loop to Print Pyramid of Stars
Autowiring Httpservletrequest in Spring Controller
How to Call an Excel Vba Macro from Java Code
Determine the Number of Pages in a Pdf File
Read Huge Excel File(500K Rows) in Java
Kafka: Failed to Update Metadata After 60000 Ms
How to Clean Project Cache in Intellij Idea Like Eclipse'S Clean
Batch Inserts Using JPA Entitymanager
Spring Boot Required Request Part 'File' Is Not Present
How to Write Unit Test for a Setter Method Which Does Not Have a Getter Method
Maven- Not Downloading New Added Dependency in Pom.Xml File
Recyclerview Not Calling Oncreateviewholder or Onbindview
How to Find the Number of Times If or Else Code Has Executed
Broadcast Receiver Is Not Working When Application Is Removed from Background
Create List of Object from Another Using Java 8 Streams
Keep the Order of the Json Keys During Json Conversion to Csv