Picking up where we left off, I want to add unit tests to my program. Now, I know, I should have been using unit tests all along. I have no excuse and hang my head in shame.
To get started, I’ve decided to add xUnit through NuGet. Easy peasy. But it won’t work. The full explanation is here. Great article. Here, in a nutshell are the steps you need to perform:
- Create an xUnit test project in the same solution as ForgetMeNot
- Make sure it runs
- Add a reference to the ForgetMeNot project
- This wil not run yet. Here is where the fun begins
- First, open up the ForgetMeNot project and change the TargetFrameworks to
<TargetFrameworks>net6.0;net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
6. Replace the output statement with
<OutputType Condition="'$(TargetFramework)' != 'net6.0'">Exe</OutputType>
7. Unload ForgetMeNot, reload it, close Visual Studio, open Visual Studio and voila! it will work
(The whys and wherefores are explained very well in the article referenced above)
NSubstitute for mocking
We are now almost ready to begin. I want to use mocking from the very beginning. Until about a weak ago, I’d have installed Moq, but I’m intrigued by NSubstitute, so I’m going to use that.
After assuring myself that the default xUnit test works, I’ll add a file called BuddyTests. In there I will add my first test: ShouldPopulateBuddies. I want to make sure that calling Init() will populate the list of buddies (actually, it could return no buddies, but right now I just want to get this test working).
[Fact]
public async Task ShouldPopulateBuddies()
{
var buddies = new List<Buddy>();
var buddy = new Buddy();
buddies.Add(buddy);
var buddyService = Substitute.For<IBuddyService>();
buddyService.GetBuddies().Returns(buddies);
var buddyListVM = new BuddyListViewModel(buddyService);
await buddyListVM.Init();
Assert.True( buddyListVM.Buddies?.Count > 0);
}
So what is going on here? First I create an empty list of Buddy objects and I create an instance of Buddy which I add to that list.
Next (and here is the cool part) I create a mock for my service with that one line
var buddyService = Substitute.For<IBuddyService>();
Remember that Substitute wants interfaces, so earlier I went to each class in my services, put the cursor on the class name and used Refactor->Extract->ExtractInterface which brought up this wonderful dialog box:

I clicked on Select Public to get the public methods and Its own file to put the new interface in a file named IBuddyService.cs. R# is even nice enough to tack the interface name onto the class declaration.
OK, enough digression. My next step is to tell the mock that when the BuddyService’s GetBuddies method is returned, it should return the list of Buddies we just created.
We are now ready to create an instance of the ViewModel and call init() on it. It will use the service we passed in (the mock) and will thus populate its list of buddies with our dummy list and the Assert will pass.
Cool, eh?
This also tells me that I need to handle the case when the list is empty. That means I need to look long and hard at Init() and possibly add another test to prove that the corner case does not cause a problem.
Wrapping Up
It turns out that simple unit tests with mocking is not all that hard to do; and nSubstitute has a lot less ceremony than Moq. I’m going to stay with it for a while and see if I run off a cliff.
Since all the source code changes are already in this blog post, I won’t update the online source until I’ve written some more tests.
Shout-out to Daniel Hindrikes for helping me get started on unit testing for MAUI
See next posting for more unit testing using Fluent asserts.






































Hello there, You’ve done a great job. I’ll certainly digg it and for my part suggest to my friends. I’m confident they will be benefited from this site.
Good post. I learn something new and challenging on sites I stumbleupon on a daily basis. It will always be interesting to read through content from other writers and use a little something from their websites.
This is my first time visit at here and i am truly pleassant to read all at alone place.
Hi Dear, are you genuinely visiting this web site on a regular basis, if so then you will without doubt obtain nice knowledge.
Вот реально ситуация — родственник начинает пить сутками, а ты не знаешь куда бежать . Моя семья с таким столкнулась недавно. Думал, справлюсь сам — нифига . Оказалось , без врачей и нормального наблюдения не обойтись. Перерыл кучу форумов — одни обещания и бабло тянут. А потом наткнулся на один проверенный вариант. Если ищете где сделать качественное выведение из запоя с госпитализацией — не ведитесь на дешёвые акции . У нас в Нижнем, кстати , тоже полно левых контор без лицензии. Вся проверенная информация ниже по ссылке: кодирование от алкоголизма нижний новгород кодирование от алкоголизма нижний новгород Честно скажу , после того как вник в детали, расставил всё по полочкам. Там и про кодирование от алкоголизма подробно расписано , и про выезд нарколога на дом . И цены адекватные, без разводов. Рекомендую не откладывать в долгий ящик.
This text is worth everyone’s attention. When can I find out more?
I am genuinely thankful to the owner of this web page who has shared this fantastic paragraph at at this time.
Hello there, You have done a great job. I’ll certainly digg it and personally suggest to my friends. I am confident they will be benefited from this site.
Hello there, You’ve done an excellent job. I’ll definitely digg it and in my opinion recommend to my friends. I’m confident they’ll be benefited from this web site.
Hi there, You’ve performed a great job. I will certainly digg it and personally recommend to my friends. I am confident they will be benefited from this website.
Hey! Someone in my Facebook group shared this website with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Superb blog and outstanding design and style.
Hello there, You have done a fantastic job. I will certainly digg it and personally recommend to my friends. I’m confident they’ll be benefited from this site.
Android kullanıcısı olarak iyi bir uygulama şart. Herkes farklı bir link atıyordu kime güveneceğimi bilemedim. En sonunda sağlam bir kaynağa ulaştım ve size de buradan bahsetmek istediğim nokta şurası: 1xbet yükle android 1xbet yükle android. Şimdi size kısaca özet geçeyim — telefonuma kurduktan sonra hiç şikayet etmedim.
Hiçbir kasma yaşamadım şu ana kadar. İşin doğrusunu söylemek gerekirse — en güvenilir uygulama bu oldu artık. Şimdiden iyi şanslar ve bol kazançlar…
Hi there, You have performed a great job. I’ll definitely digg it and for my part recommend to my friends. I’m sure they’ll be benefited from this web site.
Hello there, You have performed a fantastic job. I’ll certainly digg it and individually suggest to my friends. I’m sure they will be benefited from this website.
Whoa! This blog looks just like my old one! It’s on a totally different subject but it has pretty much the same page layout and design. Great choice of colors!
read what he said compass wallet
bilder pГҐ nagelsvamp: Svenska Pharma – kalium tabletter apotek
Hi there colleagues, good paragraph and nice urging commented here, I am genuinely enjoying by these.
Правило ответственной игры состоит в контролируемом подходе к игровым платформам.
Этот принцип включает добровольное лимитирование времени и бюджета на игру.
Участнику рекомендуется заранее выставить потолок потерь и не превышать этот лимит.
Крайне необходимо воспринимать игру только как способ развлечения, а не средство заработка.
В случае появлении признаков зависимости (погоня за проигрышем) стоит использовать тайм-аут или самоисключение.
Следование данных правил гарантирует ментальное здоровье и денежную безопасность пользователя.
https://sorrybabushka.ru/interesting/300-sberezheniya-zhiteley-ryazanskoy-oblasti-prevysili-385-mlrd-rubley.html
Принцип ответственной игры состоит в осознанном подходе к игровым платформам.
Этот принцип включает добровольное ограничение длительности и бюджета на сессию.
Участнику рекомендуется заранее определить максимальную сумму и строго соблюдать этот предел.
Крайне необходимо рассматривать игру исключительно как способ развлечения, а не источник дохода.
В случае возникновении симптомов зависимости (погоня за потерянным) стоит активировать паузу или блокировку аккаунта.
Следование данных правил сохраняет ментальное благополучие и финансовую стабильность пользователя.
https://e-transavto.ru/read/1-iyunya-v-khakasii-dozhdlivoe-nachalo-leta-270/
mexican pharmacy online mexican pharmacies mexican medicine store
Currently it appears like BlogEngine is the preferred blogging platform available right now. (from what I’ve read) Is that what you’re using on your blog?
Right now it looks like BlogEngine is the top blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?
apotek Г¶rhГ¤ngen: kamfer apotek – ringorm apotek
Excellent write-up. I definitely love this website. Thanks!
https://mexicorx.online/# buying prescription drugs in mexico
It’s a pity you don’t have a donate button! I’d most certainly donate to this superb blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will share this site with my Facebook group. Talk soon!
It’s a shame you don’t have a donate button! I’d definitely donate to this outstanding blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Chat soon!
Hello my family member! I want to say that this post is awesome, great written and come with approximately all important infos. I would like to peer more posts like this .
O segredo é esperar. Demorou, mas veio o Multiplicador 100x no Bikini Paradise. uma bolada limpo.
Whats up very cool web site!! Guy .. Excellent .. Amazing .. I will bookmark your web site and take the feeds also? I’m happy to find a lot of useful info right here in the post, we need develop extra techniques in this regard, thank you for sharing. . . . . .
从信息可信度角度评估,Cryptify Hub属于“低权威性信源”。因为它是一个民间Web3社群,品牌叫“学院”但不具备任何官方背书。社群成员分享的链接、观点、建议均代表个人,而非平台立场。导航站中的工具链接由社群成员共同维护,可能存在遗漏或过期。用户应将其作为参考线索,所有重要决策(尤其是涉及资金的操作)必须通过其他权威渠道交叉验证。
有人嫌它太简单,有人嫌它不够全。但别忘了,它就是一个导航站——简单是它的本分,不全是它的常态。Cryptify Hub的定位决定了它不可能满足所有人的所有需求。合理预期:用它快速找链接,剩下的自己来。
I am genuinely thankful to the owner of this website who has shared this enormous paragraph at at this place.
Deneyip de begenen cok oldu. Surekli adres degisiyor. En sonunda her seyi cozdum.
Ozellikle bahis ve casino sevenler icin. Su an en h?zl? cal?san 1xbet guncel giris adresi tam olarak soyle: 1xbet güncel 1xbet güncel. Ne demisler — 1xbet turkiye icin tek adres buras?.
Site s?k s?k kapan?yor diyenlere inat. Tavsiye eden c?kt? m? emin olun — canl? destekleri bile h?zl?. Baska yerde aramay?n art?k…
I am genuinely thankful to the holder of this site who has shared this great piece of writing at at this time.
Правило ответственной игры заключается в контролируемом отношении к азартным развлечениям.
Этот принцип включает добровольное лимитирование времени и бюджета на сессию.
Игроку рекомендуется заранее определить потолок потерь и не превышать этот предел.
Важно рассматривать игру только как вид досуга, а не источник заработка.
В случае появлении симптомов зависимости (погоня за потерянным) нужно использовать тайм-аут или самоисключение.
Соблюдение данных установок гарантирует ментальное здоровье и денежную стабильность игрока.
https://online-festival.ru/detail/1338-pashinyan-otvergaet-referendum-o-vybore-mezhdu-es-i-eaes.html
I loved as much as you will receive carried out right here. The sketch is attractive, your authored material stylish. nonetheless, you command get got an edginess over that you wish be delivering the following. unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield this hike.
Very descriptive post, I loved that bit. Will there be a part 2?
First of all I want to say great blog! I had a quick question that I’d like to ask if you don’t mind. I was curious to find out how you center yourself and clear your thoughts before writing. I’ve had difficulty clearing my thoughts in getting my thoughts out. I truly do enjoy writing however it just seems like the first 10 to 15 minutes are wasted just trying to figure out how to begin. Any recommendations or tips? Thanks!
Tela forrada e Big Win!
Excellent pieces. Keep writing such kind of information on your blog. Im really impressed by it
Every weekend i used to pay a visit this website, because i wish for enjoyment, as this this web page conations actually nice funny data too.
Appreciate this post. Let me try it out.
Greetings! Very helpful advice in this particular article! It’s the little changes that will make the largest changes. Thanks for sharing!
Thanks to my father who informed me about this web site, this website is genuinely amazing.
Good day! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
Wonderful blog! I found it while surfing around on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Thanks
Heya superb blog! Does running a blog similar to this take a large amount of work? I’ve very little expertise in programming however I had been hoping to start my own blog soon. Anyhow, if you have any suggestions or tips for new blog owners please share. I know this is off subject nevertheless I simply wanted to ask. Thanks a lot!