How to unit test a ViewModel with MessageCentre

LotokLotok GBMember ✭✭

In the constructor of my ViewModel I have this subscription

MessagingCenter.Subscribe(Application.Current, "updateMapJobs", UpdateMapJobs);

The problem is when I have come to write unit tests for the ViewModel. On creation I get an ArgumentNullException for subscriber and it fails on the MessageCenter line.

I have done some searching but no seen any similar issues, I could use a point in the right direction, documents or something

Thanks

Best Answer

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    If that really is right... And the problem is that it fails because its in the constructor... Find a way to move it out of the constructor. I try to avoid any code that actually does work in a constructor. That's a side-effect and leads to issues. This is a case in point.

    Can you just construct the ViewModel in the constructor, then have a Start() method called from someplace else that does the work part when running? I do that fairly often: Add a StartFeature() and StopFeature(). That way I can construct all my ViewModels in a heartbeat for fast startup. Then I can actually start the feature later, like when the user logs in... or when connectivity is established etc. And stop the feature when connectivity is lost, without the overhead of disposing of the viewmodel and making a new one, just because I need to restart something along with all the constructor overhead.

  • LotokLotok GBMember ✭✭

    That would make sense. I will test that out thanks very much. The version I am using has "To be added" in the intellisense. This is the only Forms app I manage and I hate updating its version, always breaks something and documentation is dated so I am probably a little out of date.

Sign In or Register to comment.