简体   繁体   English

Junit 对于 CompletableFuture.runAsync()

[英]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在这里,我很想知道我们如何为在 CompletableFuture.runAsync() 中编写的业务逻辑编写 junit 测试用例,例如

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我在下面写 junit 上面实现的测试用例

@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.在这里,当我运行 junits 时,它没有执行在“CompletableFuture.runAsync(()-> {”之后编写的代码,即私有方法 writeIntoCassandraTable(transaction) 和 writeIntoCassandraTable2(transaction) 没有被执行。我在 try 块中保留了断点但是控制在这一点上没有停止。这导致代码覆盖率低。帮助我理解为什么它没有被执行以及如何修复它。如果您需要更清晰或更详细的信息,请告诉我。

I would suggest switching out runAsync with supplyAsync in your original method.我建议在您的原始方法中使用supplyAsync切换runAsync Then, return something from the supplyAsync method.然后,从supplyAsync方法返回一些东西。 As for what to return, you may need to use Mockito or some other equivalent mocking library.至于要返回什么,您可能需要使用 Mockito 或其他一些等效的 mocking 库。 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.从那里开始,只需做出您的断言,您就应该有一个有效的单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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