Principal Software Engineer at Allscipts in Malvern, Pennsylvania, Microsoft Windows Dev MVP, Husband, Dad and Geek.
63430 stories
·
23 followers

Ten Design Best Practices for Azure Applications

1 Share

While the 10 design best practices for Azure applications has been around for a couple of years, it’s always nice to revisit periodically. Included in the list are:

Ten design principles for Azure applications



Read the whole story
alvinashcraft
5 hours ago
reply
West Grove, PA
Share this story
Delete

Comparing .NET Mocking Libraries

1 Share

There are quite a few different mocking libraries in .NET. Moq and NSubstitute seem to be by far the main ones I hear that developers use. I've used both of these in different projects, and really like them both. Whilst my preference leans towards NSubstitute, I'd be happy using either. Out of interest, I posted a Twitter poll to see what other people preferred, and the results and replies were really interesting!...

The winner of the poll is clear - but interestingly, a lot of the replies indicated that they used Moq just because it was the most well known / used, and they hadn't tried anything else. There was certainly a lot of love for NSubstitute in the replies, commenting that the API is much cleaner.

I thought it would be interesting to compare some of the leading libraries like for like. So I picked the top three in the poll - namely, Moq, NSubstitute, and FakeItEasy. And I'll go through some code snippets for some of the more common requirements of a mocking library. Note that I can't possibly cover every thing in this blog post, but I'll focus on the features I find myself mostly using.

But first, what does a mocking library actually do?...

What is a mocking library?

When writing a test, quite often you want to only test one particular class and method. But that method might call a dependency that calls into a database, or calls an external service. When writing an integration test, you may want to include those dependencies in your your test - perhaps using a real database span up in Docker, or an in-memory database. But what if you're only writing a unit-test (or the integration can't simulate a particular dependency)? How do you call the method you want to test, without it calling into the dependency and therefore making that database call?

Quite often in .NET codebases, you'll quite often see classes implement an interface - especially those which call into databases or make external API/service calls. For example, you might have a class called EFStockChecker which has Entity Framework code that talks to a database to check stock level. This contains implementation details - ie. it uses the Entity Framework library. This might then implement an interface called IStockChecker.

It is this interface that the rest of the codebase ideally should use - not the concrete type (implementation). The key point here is that the interface has no concept of Entity Framework, or whatever database technology we might be using. All it does is describe the intent. This is known as dependency inversion. When programming in this manor, your business logic isn't concerned with the implementation details of its dependencies. It also means that those dependences are really easy to replace with another implementation when testing.

Let's continue with the IStockChecker example...

interface IStockChecker
{
    bool IsProductInStock(string sku);
}

Nothing in the above interface indicates a database or database technology. It's just about the requirement, not how that requirement is fulfilled.

Then I might have some code in my business logic that does this...

public class OrderHandler
{
    private readonly IStockChecker _stockChecker;
    private readonly IOrderRepository _orderRepository;

    public OrderHandler(IStockChecker stockChecker, IOrderRepository orderRepository)
    {
        _stockChecker = stockChecker;
        _orderRepository = orderRepository;
    }

    public void ProcessOrder(string sku)
    {
        if (_stockChecker.IsProductInStock(sku))
        {
            _orderRepository.Create(...);
            ...
        }
    }
}

Because this code only knows about abstractions (ie. the interfaces), it's easy to run this code without using the production implementation of those interfaces. I could just create another implementations just for the test that implements those interfaces, but doesn't call the database. These test implementations are known as 'stubs'.

A mocking library allows you to simulate an interface or abstract type's implementation. You instantiate a 'mock' object of the interface, and tell that mock object what it should return if a method/property is called against that mock. You can also assert that a method/property was or wasn't called.

Some people prefer sticking to stubs over mocking libraries, but I personally prefer to avoid creating additional classes when a mocking library can do it for us. A mocking library also adds additional functionality, like as mentioned above - being able to assert/verify that a mocked method was called. You could obviously implement this yourself in your test implementation - but a mocking library can do this for you, so why reinvent the wheel?

The basic scenario we'll be using as an example

Let's start with a very simple scenario. Imagine we're testing the above-mentioned ProcessOrder method. Two interfaces are injected into the constructor. The implementation of both of them call out into a database or API (but we don't care about the data source or implementation), as we're not testing this. We only care about the logic in our ProcessOrder method. Eg. How does our ProcessOrder handle the having stock vs being out of stock.

Below is an example test to ensure that an order isn't created if there's not enough stock (using the Moq mocking library)...

[Fact]
public void GivenInsufficientStock_DoNotCreateOrder()
{
    // Arrange

    var mockStockChecker = new Mock<IStockChecker>();
    var mockOrderRepository = new Mock<IOrderRepository>();

    mockStockChecker.Setup(x => x.IsProductInStock()).Returns(false);

    var sut = new OrderHandler(mockStockChecker.Object, mockOrderRepository.Object);

    // Act

    sut.ProcessOrder();

    // Assert

    mockOrderRepository.Verify(x => x.CreateOrder(It.IsAny<int>()), Times.Never);
}

As you can see, the dependencies are mocked out. The real implementation would have called out to a database, but the class we're testing doesn't know or care about this - it just cares that whatever "IsProductInStock" is, we get a boolean back. It doesn't care where that comes from, as that's not it's responsibility. What is it's responsibility is that if IsProductInStock returns true, the class we're testing will execute ProcessOrder. And likewise, if it returns false, it does not execute ProcessOrder.

The above example shows how simple it is to tell the mock object to return false if IsProductInStock is called. This bit is just like a stub, but created for you by the mocking library.

You can also see how we can leverage the mock to verify that CreateOrder was or wasn't called. This bit is like a 'spy', but again, done for you by the mocking library.

(for a description of the different types of test-doubles - eg. dummies, fakes, stubs, spies, mocks - Martin Fowler has a post with a short description of each).

In fact, on the NSubstitute homepage, they even try to move away from these specific definitions, and state: "Mock, stub, fake, spy, test double? Strict or loose? Nah, just substitute for the type you need!".

Comparing Mocking library syntax

Okay, now we know what a mocking library does - let's move onto some syntax comparisons...

Mock creation and simple 'Returns' Setup with no parameters

Let's start with how we create a mock, then declare a return value for a method or property in a mocked object...

// Moq
var mockStockChecker = new Mock<IStockChecker>();
mockStockChecker.Setup(x => x.IsProductInStock()).Returns(true);
var sut = new TheClassIAmTesting(mockStockChecker.Object);
sut.DoSomething();

// NSubstitute
var mockStockChecker = Substitute.For<IStockChecker>();
mockStockChecker.IsProductInStock().Returns(true);
var sut = new TheClassIAmTesting(mockStockChecker);
sut.DoSomething();

// FakeItEasy
var mockStockChecker = A.Fake<IStockChecker>();
A.CallTo(() => mockStockChecker.IsProductInStock("")).Returns(true);
var sut = new TheClassIAmTesting(mockStockChecker);
sut.DoSomething();

NSubstitute certainly seems the cleanest here, not requiring .Object or a .Setup call and lambda. Note that Moq also has another syntax, where you don't need to use .Object to get at the mocked object, but if you do this - you have the inverse problem, where you have to do Mock.Get(myMock) to do any setup.

Moving forward, I'll omit the mock instantiation and the SUT call for brevity.

'Return' Setup with explicit parameters

What about if your method takes parameters? Eg, we know our IsProductInStock method does take a 'sku' parameter...

// Moq
mockStockChecker.Setup(x => x.IsProductInStock("banana")).Returns(false);

// NSubstitute
mockStockChecker.IsProductInStock("apple").Returns(true);

// FakeItEasy
A.CallTo(() => mockStockChecker.IsProductInStock("orange")).Returns(true);

This is very similar to the previous example - you just specify the parameter value when setting it up.

'Return' Setup regardless of parameter values

And what if your method takes a parameter, but you don't care what values are passed to it by the code you're testing?...

// Moq
mockStockChecker.Setup(x => x.IsProductInStock(It.IsAny<string>())).Returns(true);

// NSubstitute
mockStockChecker.IsProductInStock(Arg.Any<string>()).Returns(true);

// Or NSubstitute can also do this to specify that all arguments can be ignored
mockStockChecker.IsProductInStock(default).ReturnsForAnyArgs(true);

// FakeItEasy
A.CallTo(() => mockStockChecker.IsProductInStock(A<string>.Ignored))).Returns(true);

They all have similar syntax here. Moq uses It.IsAny<>() syntax, NSubstitute uses Arg.Any<>(), and FakeItEasy uses A<string>.Ignored. In NSubstitute, you can also use ReturnsForAnyArgs and the parameters will be ignored. In the above example, I've used the default keyword when doing this to make it more clear that these values are ignored - I could have put "", or any other value, but I think using default makes it more clear.

Throwing exceptions

Quite often you want to have tests testing how your code handles a dependency throwing an exception. Mocks allow you to simulate exceptions being thrown...

// Moq
mockStockChecker.Setup(x => x.IsProductInStockAsync("")).Throws(new NullReferenceException());

// NSubstitute
mockStockChecker.IsProductInStock("").Throws(new NullReferenceException());

// FakeItEasy
A.CallTo(() => mockStockChecker.IsProductInStock("").Throws(new NullReferenceException());

All of these are very similar to their Returns counterpart. Just replacing Returns with Throws.

Verifying a mocked method is or isn't called

Another really useful feature of mocking libraries is that you can spy on whether a mocked method was called or not. We saw an example of this in the GivenInsufficientStock_DoNotCreateOrder code snippet earlier in this post, where we verified that CreateOrder wasn't called when there was insufficient stock.

// Moq
mockOrderRepository.Verify(x => x.CreateOrder()); // Defaults to Times.AtLeastOnce
mockOrderRepository.Verify(x => x.CreateOrder(), Times.Never);
mockOrderRepository.Verify(x => x.CreateOrder(), Times.Once);
mockOrderRepository.Verify(x => x.CreateOrder(), Times.Exactly(2));
mockOrderRepository.Verify(x => x.CreateOrder(), Times.Exactly(3));

// NSubstitute
mockOrderRepository.Received().CreateOrder();
mockOrderRepository.DidNotReceive().CreateOrder();
mockOrderRepository.Received(1).CreateOrder();
mockOrderRepository.Received(2).CreateOrder();
mockOrderRepository.Received(3).CreateOrder();

// FakeItEasy
A.CallTo(() => mockOrderRepository.CreateOrder()).MustHaveHappened();
A.CallTo(() => mockOrderRepository.CreateOrder()).MustNotHaveHappened();
A.CallTo(() => mockOrderRepository.CreateOrder()).MustHaveHappenedOnceExactly();
A.CallTo(() => mockOrderRepository.CreateOrder()).MustHaveHappenedTwiceExactly();
A.CallTo(() => mockOrderRepository.CreateOrder()).MustHaveHappened(3, Times.Exactly);

I've included a few examples above showing how to check for different numbers of calls to a mocked method. This particular method I've verifying has no parameters, but all the libraries support verifying the a call was made with specific parameter values, or any parameter values.

Summary

I certainly haven't touched on all the functionalities that exist in mocking libraries - but rather focused on the features I tend to mostly use. There is plenty of other functionality - eg. working with events, verifying the order of method calls, etc, etc. If there are any comparisons or examples you feel really belong in this post, please do let me know.

The aim of this post isn't to say one library is better than another, as when it comes down to it, they all pretty much do the same thing. The purpose of this post is just to provide a side-by-side comparison of some of the syntax, to hopefully give the you a feel of what mock creation and setup looks like across these different libraries.

Read the whole story
alvinashcraft
5 hours ago
reply
West Grove, PA
Share this story
Delete

C# Digest Issue #329

1 Share

this week's favorite

Building Windows Terminal with WinUI

WinUI and Windows Terminal have a strong relationship that goes back to the origins of Windows Terminal. This blog post goes into the history and architecture of how these two technologies came together.

SIMD - Accelerated Generic Array Library

Single Instruction, Multiple Data (SIMD) units refer to hardware components that perform the same operation on multiple data operands concurrently. The concurrency is performed on a single thread, while utilizing the full size of the processor register to perform several operations at one. This approach could be combined with standard multithreading for massive performence boosts in numeric computations.

The future of .NET Standard

Since .NET 5 was announced, many of you have asked what this means for .NET Standard and whether it will still be relevant. In this post, I’m going to explain how .NET 5 improves code sharing and replaces .NET Standard. I’ll also cover the cases where you still need .NET Standard.

Myth: Native allocations are fast

Lately I have been dipping my toes into unmanaged programming with C#. The goal was to improve the performance of some data structures that I have been working on. I thought that, maybe, I could improve the performance of them by using some unmanaged code. I noticed in the profiler that a lot of the time was just wasted on allocating memory and my initial thought was that this might be faster if I allocate my objects per Marshal.AllocHGlobal instead of good old new().

Assembly Versioning and DLL Hell in C# .NET: Problems and Solutions

I don't know about you, but reference conflicts in .NET led me to tears multiple times. I like to deal with logical challenges, software design, and performance. Not dependency issues and strange assembly load conflicts.

jobs

C# Developers are in demand on Vettery

Vettery is an online hiring marketplace that's changing the way people hire and get hired. Ready for a bold career move? Make a free profile, name your salary, and connect with hiring managers from top employers today.

Read the whole story
alvinashcraft
5 hours ago
reply
West Grove, PA
Share this story
Delete

PPP 303 | Project Management Career Advice for Women--and Men--with Elise Stevens

1 Share

Advocate for Women in Project Management

I'm excited to share this conversation with my friend Elise Stevens. Her work advocating for women in project management is an inspiration to me personally, and the insights she shares today are helpful to both men and women.

Learn more about Elise at elisestevens.co.

Join Us for our Virtual Project Management Training Program!

Learn how to improve your ability to lead and deliver! Join us this fall for the same project management program we deliver in-house at organizations around the world! Learn more at PeopleAndProjectsPodcast.com/learning. Use a coupon code of VirtualPM20 to save $150 USD on the entire program!

Let's Stay In Touch!

I hear from listeners almost every day and I love it! How about you and I connect on LinkedIn? Go to https://PeopleAndProjectsPodcast.com/LinkedIn and Follow me (I've maxed out the connections but if you Follow me, I'll Follow you back!)

Also, all of our other workshops and keynotes are available in a virtual format. Whether you have a live or virtual event, we can help you invest in your team. Learn more at https://i-leadonline.com/keynotes. Thanks!

Thank you for joining me for this episode of The People and Projects Podcast!

Talent Triangle: Strategic and Business Management

 

I Dare You and The Dweller on Coyote Hill by Little Glass Men is licensed under an Attribution License

 





Download audio: https://traffic.libsyn.com/secure/peopleandprojectspodcast/303-EliseStevens.mp3?dest-id=107017
Read the whole story
alvinashcraft
14 hours ago
reply
West Grove, PA
Share this story
Delete

Your Guide to Microsoft Surface @ Ignite 2020

1 Share

This year’s move to digital for Microsoft Ignite 2020 has created new opportunities for you to connect with Microsoft experts and technology professionals from around the globe. Ignite represents an opportunity for you to discover the latest developments in productivity, find innovative ways to build solutions, migrate and manage your infrastructure, all from the comforts of your own home.

 

This year you'll find Surface throughout Ignite in announcements, keynotes, digital breakout sessions, and on demand sessions. In addition to Ignite Sessions, the Surface team will be launching a set of digital skilling sessions to provide a deeper level of technical content that you have come to expect from Ignite. You'll be able to discover all of the great content landing at Ignite on the Surface page in the Virtual Hub launching at 8:00 AM on Tuesday, September 22.

 

Microsoft Ignite Registration

 

Don’t miss the digital-only Microsoft Ignite! There is no cost to attend and registration is now open for all attendees. Sign up today for full access to all the information and innovative content packed into our new two-day agenda.

 

Wherever you are, we’re coming to you! So get ready to connect with Microsoft experts, technology professionals and customers from around the world during this exciting digital event.

 

Event Details

  • Where: Digital Event
  • When: September 22nd – September 24th, 2020
  • Why: Get a look on Microsoft latest technology

 

Microsoft Ignite 2020

Registration is now open and free to all attendees

 

Register-Now-Button-1.png

 

Surface Sessions and Skilling Launched at Ignite

Ignite Sessions

Below are the list of sessions where specific news, announcements, and Surface owned content will land at Ignite as part of the Ignite catalog and scheduled programming. Sessions will be repeated across time zones, so be sure to check out the Ignite session catalog to find a time that works best with your schedule.

 

Session Type

Session Topic

Microsoft Speaker

Key Segment

Building digital resilience

Satya Nadella

Key Segment

M365 Keynote : The Future of Work

Jared Spataro

Live Session

Driving Innovation for Modern Work with Surface Hub and Duo

Pete Kyriacou + Others

On Demand Catalog

Surface as the Modern Endpoint: Realize the Best of Microsoft 365

Ali Akgun

Ask the Experts

Ask the Expert: Driving Innovation for Modern Work with Surface Hub and Duo

Dave Alles

 

Following the event, these sessions recordings will also be copied to the Surface page in the Virtual Hub and posted to the Surface YouTube channel.

 

Surface Skilling Sessions

The list of sessions below are the deeper level of session content and skilling that will be launched and timed with Ignite. They are included in the Virtual Hub and showcased on the Surface YouTube channel. Content will go live on Tuesday, September 22 at 8:00 AM PST.

 

Session Type

Session Topic

Microsoft Speaker

On Demand

Highly Secure PCs – Best-in-class endpoint Security from Microsoft 

David Weston / Mark Scheffler

On Demand

Surface Security: Chip to Cloud Modern Endpoint Protection from Microsoft

Mary Beth Anderson / Bob Combs

On Demand

Built to be connected – Surface Pro X and Windows on ARM in a remote world

Jesse Kopavi / Marc Sweetgall

On Demand

Deploy, Manage, and Enable Productivity with Surface Duo in the Enterprise

Kimmo Lehtosalo / Karan Dhillon / Natalia Urbanowicz / Vineet Nair Thuvara

On Demand

Surface Tools: Manage Docks with SEMM, Seamless support through SDT4B

Harshitha Murthy

On Demand

Zero Touch Deployment with Surface & AutoPilot

Mo Salah / Sean McLaren

On Demand

Surface Hub: The Future of Collaboration from Anywhere

Yoav Barzilay / Matthew Shaw

On Demand

Microsoft Surface in Healthcare: Technology and collaboration for better experiences, insights and care

Jessica Goldberg

Surface Social Amplification

 

Watch for Microsoft Ignite posts on Surface LinkedIn and Surface Twitter leading up to and throughout the global, digital event. We'd love your promotion of our Surface presence by sharing posts that unveil Surface news and detail Surface sessions – both live and on-demand. Look for curated Surface content on LinkedIn Elevate to share with your network and be sure to use the combination of these hashtags: #SurfaceForBusiness and #MSIgnite.

 

Be sure to leverage links and point attendees to the Surface page in the Virtual Hub as a central location to explore all of the news the Surface team is launching at Ignite and beyond.

 

Surface Virtual Hub

Launching, Tuesday, September 22, 2020 | 8:00 AM PST

 

Location: Surface page in the Virtual Hub

 

We are excited to be launching the Virtual Hub at Ignite! This evergreen page will be a one-stop resource designed to enable the IT Community to explore content, resources, and engagement opportunities throughout the year across whatever channel or portal it may live.

 

The Virtual Hub launching at Ignite will provide a single source location and landing page for attendees to explore news, announcements, content, skilling, and more both aligned to Ignite and beyond. This central page will enable the Surface team to drive greater visibility and connections with our ITPro community.

 

Following the event, Ignite session content will be moved from the Ignite Catalog to the Surface page in the Virtual Hub and posted to the Surface YouTube channel. Additionally, resource links for each of the Surface sessions in the Ignite catalog will point attendees to the Virtual Hub, where IT Pros can go deeper on content and training throughout the year.

 

Read the whole story
alvinashcraft
14 hours ago
reply
West Grove, PA
Share this story
Delete

Building a Database Application in Blazor - Part 3 - CRUD Edit and View Operations in the UI

1 Share
Article 3 describing how to build the CRUD Viewer and Editor Presentation/UI Layer in a Blazor Database Application
Read the whole story
alvinashcraft
14 hours ago
reply
West Grove, PA
Share this story
Delete
Next Page of Stories