简体   繁体   中英

Junit for CompletableFuture.runAsync()

I would like to say Thanks to each one of you to share your knowledge and time with all of us. Here, I'm curious to know how can we write junit test case for a business logic written within CompletableFuture.runAsync() eg

public class Loan{
public Transaction writeIntoCassandra(Transaction transaction){
   private startTime = System.currentTimeMillis();
   CompletableFuture.runAsync(()-> {
         try{
                writeIntoCassandraTable(transaction);
            }
         catch(JsonConversionException e){
         }         
      });
   CompletableFuture.runAsync(()-> {
         try{
                writeIntoCassandraTable2(transaction);
            }
         catch(JsonConversionException e){
         }         ​
     ​});
return transaction;
}
}

I'm writing below junit test case for above implementation

@InjectMocks
private Loan loan;

    public void writeIntoCassendraTest(){
  String jsonTransaction = "";
  ObjectMapper objectMapper = new ObjectMapper();
  Transaction transaction = objectMapper.readValue(jsonTransaction, Transaction.class);
  loan.writeIntoCassendra(transaction);
  //assertThat();
}

Here, when I am running junits it is not executing code written after "CompletableFuture.runAsync(()-> {" that is private methods writeIntoCassandraTable(transaction) and writeIntoCassandraTable2(transaction) are not getting executed. I kept breakpoint withing try block but control is not stopping at this point. Which is resulting low code coverage. Help me to understand why it is not getting executed and how it can be fixed. Let me know if you need more clarity or details.

I would suggest switching out runAsync with supplyAsync in your original method. Then, return something from the supplyAsync method. As for what to return, you may need to use Mockito or some other equivalent mocking library. If not that, maybe there is some dummy values/objects you could use instead? From there, just make your assertions, and you should have a working unit test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM