MediatR gets multiple handlers instances when expected single - dryioc

I'm using Generic Type Requests and Handlers.If I have more than one IAsyncRequestHandler DryIoc is resolving multiple instances, instead of a single instance, causing MediatR to throw an exception.How can I solve this problem?Please check this behavior at Net Fiddle here.(Note that in this example Generic Type is only used to prove the point - MediatR throwing the exception - In my production code, Generic Types are actually needed)

The fix for your problem is out with DryIoc 2.10.1.
The reason details are in issue #446.
Update:
Regarding sample with class GoodMorningRequestHandler<T> : IAsyncRequestHandler<GoodMorningRequest, string> the exception is bit misleading but it is here as expected.
Reason is that above mapping is not registered at all by DryIoc RegisterMany. It happens because RegisterMany checks that service type (IAsyncRequestHandler<GoodMorningRequest, string>) should supply open-generic parameter T for implementation GoodMorningRequestHandler<T>, and obviously it cannot do that. Therefore this service type is filtered out.
After that, the remaining implementation would be HelloRequestHandler<T> which does not match to resolved IAsyncRequestHandler<GoodMorningRequest, string>, so the exception.
To confirm for yourself try to just register explicitly:
container.Register(typeof(IAsyncRequestHandler<GoodMorningRequest, string>), typeof(GoodMorningRequestHandler<>)). It will throw the exception. In comparison RegisterMany designed to be more tolerant, therefore it will just skip this pair.

Related

What is Never in PassthroughSubject?

For an class in SwiftUI to conform to BindableObject, it has to have a Publisher, usually didChange, which in all of the SwiftUI documentation and videos I've seen so far, is a PassthroughSubject.
For example, if you have a class called TestObject, didChange might equal PassthroughSubject<TestObject, Never>(). I understand that the first type is the type of the data that the PassthroughSubject passes on, but what is Never? What is its purpose and are there any scenarios where the second type is not Never?
The second type provided to PassthroughSubject is the type used in case of failure.
final class PassthroughSubject<Output, Failure> where Failure : Error
The only requirement for this type is to conform to Error.
You can use an error type when the way you get your data can produce an error, like a network error for example.
The accepted answer does not address what Never is and why we may use it with a PassthroughSubject.
Never is defined as a enum with no cases. This means it can never be constructed. Sounds useless. However it can very useful to make sure functions behave as expected.
For example fatalError. fatalError will never return because it crashes the application. So you might be tempted to declare it as:
func fatalError() {}
However this would not be correct. The above function is actually returning an empty tuple (like all functions declared as above in swift). To be type correct we want to let the compiler know that if this function is called it will never return to the code that originally called it. Therefore we can use Never.
Never in PassthroughSubject
Sometimes we want Subjects that can never send errors. By declaring:
PassthroughSubject<TestObject, Never>()
you are saying that this subject will never fail with an error. So in our code we can't call the following because we can't construct a Never type to pass into the .failure:
subject.send(completion: .failure(<Nothing to construct here>))
For example: Let's say we had a timer and we wanted to publish events every 5 seconds. We could use a PassthroughSubject to send messages every 5 seconds to its subscribers. However we know it can't fail so to be clear to any consumers of our api that they don't need to worry about handling the failure case we can declare the PassthroughSubject with Never as the Error type.
Note:
The stream can still be terminated using the following:
subject.send(completion: .finished)

Guice Explicit Bindings Not Matching

I have a strange problem with Guice not using the explicit binding defined in a Guice Module. It's a simple mapping of an Interface to a Class.
I have followed it via the debugger and can see in the InjectorImpl.findBindingsByType() the bindings MultiMap does contain the binding in question. However it returns null and then throws an exception that no implementation is bound (see below). The bound type is an interface so clearly it can't new it without using the binding.
1) No implementation for org.example.module.approval.ApprovalController was bound.
Did you mean?
org.example.module.approval.ApprovalController bound at org.example.module.ApBaseModule.configure(ApBaseModule.kt:88)
org.example.module.approval.ApprovalControllerImpl bound at org.example.module.approval.ApprovalControllerImpl.class(Unknown Source)
while locating org.example.module.approval.ApprovalController
for the 1st parameter of org.example.module.invoices.delegates.BeginApprovalDelegate.<init>(Unknown Source)
while locating org.example.module.invoices.delegates.BeginApprovalDelegate
I have tried using the Execute Expression tool in the debugger to call the equals methods on the TypeLiteral and the MultiMap entry it should match. This does return false. However I can't figure out why. Interestingly if I call toString on each and test the equality it returns true.
The JavaDocs I found don't specify the equality criteria for a Type Literal and I am struggling to follow the logic in the Guice source. What is it testing besides the conical name of the class? Does the Class Loader come into it?
The reason I ask is that the effected class is stored inside a separate "plugin" jar which my app loads via a Child Class Loader at startup. So it's a different class loader to most of the app.
Any suggestions regarding where to look next would be greatly appreciated.

Mockito Verify method not giving consistent results

I'm learning GwtMockito but having trouble getting consistent verify() method results in one of my tests.
I'm trying to test the correct GwtEvents are being fired by my application. So I've mocked the Event Bus like this in my #Before method:
eventBus = mock(HandlerManager.class);
This test passes as expected:
// Passes as expected
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
I wanted to force the test to fail just to know it was running correctly. So I changed it to this and it still passes:
// Expected this to fail, but it passes
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
verifyZeroInteractions(eventBus).fireEvent(any(ErrorOccurredEvent.class));
This seems contradictory to me. So I removed the first test:
// Fails as expected
verifyZeroInteractions(eventBus).fireEvent(any(ErrorOccurredEvent.class));
Finally I added an unrelated event that should cause it to fail
// Expected to fail, but passes
verify(eventBus).fireEvent(any(ErrorOccurredEvent.class));
verify(eventBus).fireEvent(any(ModelCreatedEvent.class)); // This event is not used at all by the class that I'm testing. It's not possible for it to be fired.
I'm not finding any documentation that explains what's going on. Both ErrorOccurredEvent and ModelCreatedEvent extend GwtEvent, and have been verified in manual testing. Am I testing my EventBus incorrectly? If so, what is a better way to go about it?
Update
I've done some additional experimenting. It appears to be an issue I'm having with the Mockito matcher. When I get the test to fail the exception reports the method signature as eventBus.fireEvent(<any>) so it doesn't appear to be taking into account the different classes I'm passing into the any method. Not sure what to do about this yet, but including it here for anyone else researching this problem.
The method you're looking for is isA, instead of any.
This doesn't explain my first attempt to force the test to fail, but it does explain the other confusion. From the Mockito documentation:
public static T any(java.lang.Class clazz)
Matches any object, including nulls
This method doesn't do type checks with the given parameter, it is
only there to avoid casting in your code. This might however change
(type checks could be added) in a future major release.
So by design it doesn't do the type checks I was hoping for. I'll have to work out another way to design these tests. But this explains why they weren't behaving as I expected.

How to use Moq to simulate exceptions thrown by the StackExchange.Redis library?

I'm working on a project where I would like to use the StackExchange.Redis library to connect to a Redis database. In addition, I'd like to use Moq for the mocking library in our unit tests, but I'm running into a roadblock that I need some help to resolve.
My specific issue, is that I have a command/response architecture and I'm trying to test a cache "wrapper" that checks if a command can be satisfied by the cache before doing the actual work to return the response. An important consideration is that cache failures should never stop a request from being handled, so I want to to mock out certain failures for the StackExchange.Redis IDatabase interface. However, I can't seem to figure out how to throw a RedisException from my mocked object. For example, I'd like to just use the following code, but it doesn't compile because there's no public constructor for the exceptions thrown by this library.
Mock<IDatabase> _mockCache = new Mock<IDatabase>();
// Simulate a connection exception to validate how the cache layer handles it
// THIS DOESN'T COMPILE THOUGH
//
_mockCache.Setup(cache => cache.StringGetAsync("a", CommandFlags.None)).Throws<RedisException>();
Is there a better way to mock up failures within the StackExchange.Redis library? I feel like I'm missing something obvious either with Moq or with how to test against this library.
You can always use FormatterServices.GetUninitializedObject to create an instance of a class without running any constructor:
Creates a new instance of the specified object type.
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.
So your setup could look like this:
var e = (RedisException)FormatterServices.GetUninitializedObject(typeof(RedisException));
Mock<IDatabase> _mockCache = new Mock<IDatabase>();
_mockCache.Setup(cache => cache.StringGetAsync("a", CommandFlags.None)).Throws(e);
It's a little hackish; since no constructors are run, you should not rely on a valid state of the RedisException instance.

Useful additional output to NoResultException for JPA-Criteria Selections

Whenever a CriteriaQuery in JPA2 does not yield a result, a NoResultException is thrown. This exception is not very useful in the sense that only context-information regarding line numbers where the exception is thrown might give some indication what went wrong.
I would like to have some speaking output "Looking for a class of type and the restrictions applied where and ". It seems, the CriteriaQuery is rather shy on such information, however it seems, with a combination of reflection and getter methods I will eventually get all information I want but it will be quite messy and cumbersome.
Is there a better way to retrieve the data, which went into the CriteriaQuery-Object?
As long as you are sticking to the JPA API, public interface of CriteriaQuery is all you have.
If you are ready to go implementation specific and use Hibernate implementation, there is more available via casting it to org.hibernate.ejb.CriteriaQueryImpl. For example render method seems to provide access to nested class that have getQueryString method.
Most likely some similar ways can be found from other JPA implementations.