How to Unit Test a ViewModel with async method.

前端 未结 1 1609
既然无缘
既然无缘 2021-02-10 03:54

I am not sure where to start but let me give you a brief idea on where I am and what I want to achieve. I am quite new to Unit Testing on MVVM and having difficulty on testing t

相关标签:
1条回答
  • 2021-02-10 04:37

    Your method GetTasksAsync should return a Task so you can actually wait for it.

    I recommend this series on Channel9 an specially this episode explaining your problem.

    Just to make is clear: Simply changing the signature of GetTasksAsync to

    Task GetTasksAsync();
    

    allows you to do this:

    var t = GetAsync();
    t.Wait();
    Assert(...);
    

    In case you really want to test the command in your unit tests and not the actually method called by the command you can use a field in your ViewModel to store the task to await (not so clean) or replace your DelegateCommand by something like described in this post: Awaitable DelegateCommand

    Update: In addition to the blog post and considering you are using PRISM, you should have a look a Project Kona from the same team as PRISM. They actually implemented DelegateCommand to support AsyncHandlers

    0 讨论(0)
提交回复
热议问题