How to mock calls made to Durable Entities in Azure durable functions? - azure

I'm using MOQ to mock a durable entity, but seeing this error:
Extension methods (here: DurableContextExtensions.CallEntityAsync) may
not be used in setup / verification expressions.
Here's how I'm doing it:
mockContext.Setup(e => e.CallEntityAsync<List<string>>(It.IsAny<EntityId>(), "EntityFunctionName"))
.ReturnsAsync(new List<string>() {"one", "two", "three" });
Is there any way I can mock calls to my durable entity?

As of Durable Functions 2.3.0, all of our extension methods are now baked directly into the interface, so it should be substantially easier to use Moq with all of these methods and their overloads.
Edit: The previous answer below covers why the previous extension method approach made this dificult.
So this is an inherent limitation of how Moq works with extension methods.
Unfortunately, in the meantime, you will need to find out the core method on IDurableOrchestrationContext that is called by the extension method that provides the overload you are using.
For instance, in this case, DurableContextExtension.CallEntityAsync(EntityId entityId, string operationName) is calling IDurableOrchestrationContext.CallEntityAsync(EntityId entityId, string operationName, object operationInput), with a value of null for operationInput. You can find this by looking at the source code.
This is obviously not an ideal way for mocking, as without looking at our source code, it is difficult to tell if you are attempting to mock an extension method or not at the time of writing your tests. You can use a Moq analyzer to at least catch these errors at compile time, but it still won't tell you which method signature to mock to get rid of the error.
We are proposing getting rid of extension methods altogether for this reason, and just putting all of these signature overloads as interface methods directly, so you can mock any of them safely. This is a breaking change for customers who write their tests by directly implementing the interface, so we are trying to keep this change out of a patch release, and only in a minor release with clear guidance of how to fix those broken by these changes. Look for this to be fixed in version 2.3.0 of the extension.

Related

Azure Functions .Net 5: Is it possible to implement POCO binding somehow?

When moving my functions to .net5 I faced the fact that POCO binding that worked fine with 3.1 is not applicable with .net 5 anymore for some reason. They say it will be implemented at some point maybe, but for the certain reasons I need it now. Tried to find some hacky way to implement this, but failed. The best thought I had was to implement explicit operator in my DTO object which will cast HttpRequestData to it's type, but the problem is that HttpRequestData is an abstract type, and it's concrete implementation type is internal. After that I tried to cast the input parameter to HttpRequestData in middleware with reflection, but parameters are stored in IReadOnlyDictionary which is immutable. So I ran out of ideas now. Maybe someone found workaround to this and can kindly share, would be much appreciated.
I suppose you're using the "dotnet-isolated" mode (only way to run on .NET 5).
I'm trying to find a more elegant solution to this as well.
Meanwhile, what I did was to deserialize the data myself, inside the function.
var body = await new StreamReader(request.Body).ReadToEndAsync();
var myobject = JsonSerializer.Deserialize<MyPocoClass>(json);
I would really prefer if the runtime did it by itself, but I couln't find a way yet. I read somewhere that it is possible to create our own binding code, but I haven't tried it.
I noticed that I could bind to individual properties of the json payload, but not to an object...
I hope this arrives in Azure Functions v4 + .NET6, since it is right around the corner.

Is there an alternative to RETURNS_DEEP_STUBS for mocking chained methods with Mockito?

I have a db service save() method which allows method chaining:
#Service
public class Service {
...
public Service save(...) {
...
return this;
}
and this works just great as:
service.save(this).save(that).save(other);
When I come to mock it with Mockito though it breaks unless I use
Service serviceMock = mock(Service.class, RETURNS_DEEP_STUBS);
IIUC though, the use of RETURNS_DEEP_STUBS is considered bad. Is there a better way to mock a class with method call chaining?
Your pattern for save is very similar to a Builder pattern, which makes the question similar to "How to mock a builder with mockito" elsewhere on SO.
Per David Wallace's answer there, you can write an Answer that detects whether the mock is an instance of the return type of the method, and return the mock in only that case. This functionality was also built into the Mockito library as RETURNS_SELF in Mockito 2.0. As with any Answer, you can use this on any specific method call with thenAnswer or as the second parameter of mock to make it the default answer, but bear in mind the Mockito documentation warning that methods with generous return types (e.g. Object) will return the mock whether or not that was intended.

What do I use to replace ToNullSafeString() removed from AutoMapper 3?

I have code using AutoMapper 3.2.1.0 that uses the method ToNullSafeString().
I upgraded the NUGet package to 4.1.1.0, and I can no longer find the method in their package.Does anyone know the recommended approach to replacing the function? Is there a new construct that is functionally equivalent? If so, I cannot figure what it is. Nor can I find any mention of why it was removed.
This question has actually been answered pretty well in a couple of comments below it. For completeness, here are a couple of actual implementations of solutions.
Short answer
Probably both the simplest and the best solution: Replace all instances of .ToNullSafeString() with ?.ToString(). This does the same, but uses functionality built into newer versions of .Net instead of relying on an external extension method.
Alternative answer
If you've got a bunch of calls to the ToNullSafeString() method from the earlier version Automapper, and for some reason or other you can't or don't want to go through all your code and edit it away right now, you can use this instead.
Add the following class to your project, and make sure it can be reached from any classes that previously called the Automapper-method. Those calls will then automatically point to this instead.
public static class NullSafeStringHelper
{
public static string ToNullSafeString(this object value)
{
return value?.ToString();
}
}

Why is the compiler optimizing out the parameters when using Postsharp with an async method

I started using a Web API cache which I add to particular methods by using an aspect [Cache]. Everything worked great. Later on I changed this method to be async, but since then the compiler started throwing following warnings:
The parameter 'region' of method 'GetTree(System.String,
System.String, System.String[])' has been optimized out by the
compiler and will not be available to the aspect. Disable compiler
optimizations to access the parameter.
Here you can see an example of how I am using Postsharp:
[Cache]
public async Task<IEnumerable<Node>> GetTree(
[FromUri] string region,
[FromUri] string language,
[FromUri] string[] networks)
{
...
await ...
}
What do I need to do in order to get rid of the warning?
The C# compiler optimizations remove the parameters from the state machine class if these parameters are not used anywhere inside the async method. This happens regardless of whether you use PostSharp or not. PostSharp shows you the warning to notify that the removed parameters cannot be accessed inside the aspect.
It's recommended to upgrade to the latest build of PostSharp - the newer versions can handle this issue by re-introducing the missing parameters back into the state machine.
If you cannot upgrade, then the workaround is to disable "Optimize code" in the build page of the project properties for release builds (it's disabled for debug builds by default).

How can I use Groovy's mock.interceptor package to mock an objects constructor?

In my attempt to mock an object in Groovy using the mock.interceptor package:
def mock = new MockFor(TheClass);
mock.demand.theMethod{ "return" }
mock.use {
def underTest = new TheClass()
println underTest.theMethod()
}
The problem I have is when creating TheClass() in the use{ block, it uses the actual constructor which, in this circumstance, I'd rather it not use. How can I create an instance of this class so I can test the method I do care about, theMethod, without needing to use the constructor?
Using EasyMock/CE, mocks can be made without using the constructor, but am curious how to achieve that in Groovy.
I recently saw a presentation by the author of GMock and it has some hooks to allow "constructor" mocking which I think is what you are after.
e.g.
def mockFile = mock(File, constructor('/a/path/file.txt'))
This library differs from that "built in" to groovy, however it looked very well written, with some thought put into the kinds of things you want to mock and more importantly the error messages you would get when tests should fail.
I think this is what you are after. I would say use constructor mocking with care - it could be a smell that you should inject a Factory object, but for some things it looked to work well.
You can use the interceptConstruction flag when calling MockFor, see
MockFor.

Resources