MRUnit and AvroMapper - mapreduce

AvroMapper requires 2 parameters:
public static class AvroRecordMapper
extends AvroMapper <MyRecord,Pair <CharSequence,CharSequence>>
and mapDriver requires 4 parameters:
K1 V1 K2 V2
Can I use MRUnit for unit tests with AvroMapper?

Related

xUnit Moq setup failed to detect the method when a object is passed in

I'm very new to unit test and moq. In my .net core 3.1 project I', using xUnit and Moq to write unit test. I have below scenario that I couldn't figure out why the moq can't detect my function.
I have configured my Unit test as below,
VASTest t = new VASTest()
{
RecurringAndOneOffChargeID = 2
};
_dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(t))
.ReturnsAsync(() => true);
_dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(2))
.ReturnsAsync(() => true);
In my test function I have blow two functions which I'm trying to moqup with above setup,
var result1 = _VASBillingDataAccess.CreateVASBillingRunRecurringChargesTest(tvt).Result;
var result2 = _VASBillingDataAccess.CreateVASBillingRunRecurringChargesTest(2).Result;
I have blow class in my models,
public class VASTest
{
public int RecurringAndOneOffChargeID { get; set; }
}
when I'm running the unit test, result1 is always false, but result2 is always true.
Could you please give me some suggestion how to fix the result1?
Thank you.
Your setup:
VASTest t = new VASTest()
{
RecurringAndOneOffChargeID = 2
};
_dataserviceMock.Setup(x => x.CreateVASBillingRunRecurringChargesTest(t)).ReturnsAsync(() => true);
will only work if that instance of VASTest - t - is used in the SUT invocation, or you implement your own equals method for the VASTest class that can resolve if 2 instances of VASTest are equal to each other. If either of those are not the case then you're performing the equality check by reference and that will not be satisfied. Your other setup using the int (2) works as an int is a value type and an equality check is always done on the value iself.
I'd just do the following if I wasn't implementing IEquatable<T>:
_dataserviceMock.Setup(x =>
x.CreateVASBillingRunRecurringChargesTest(
It.Is<VASTest>(t => t.RecurringAndOneOffChargeID.Equals(2))))
.ReturnsAsync(() => true);

how to unit test FP function that uses dependency

Trying to understand how functional programmers unit test functions that have dependencies without dependency injection.
In order to unit test with mocks, you can either provide your dependency through the method signature or through a constructor/constructor-like mechanism.
so if you have function composition like this:
a -> b -> c -> d
If you have d talking to some dependency, how does a get unit tested?
Where ever the dependency is kept, I'd want to have it unit tested.
I want to know what approach functional programmers take.
You can unit test depenent code with proper scoping, mocking, and dependency injection. Let me show you what I mean.
const square = x => x ** 2
const isOdd = x => x % 2 === 1
const addDependentValue = dependency => x => x + dependency.value
const mockDependency = { value: 5 }
it('filters out evens, squares, and adds value from dependency', () => {
const output = pipe([
filter(isOdd),
map(square),
map(addDependentValue(mockDependency)),
])([1, 2, 3, 4, 5])
assert.deepEqual(output, [6, 14, 30]) // OK
})
We scoped our function addDependentValue so that the return could "see" the dependency (it's in scope). In our test, we mocked our dependency with mockDependency. This would enable us to derive a predictable result in our test. In a less contrived example, your mock should mirror the interface of whatever dependency you are mocking. Finally, we inject the mockDependency in our test, allowing us to reasonably test this pipeline.
how does a get unit tested?
a is pure, so you can just write a simple unit test for it
// if a is square
it('squares', () => {
assert.strictEqual(square(3), 9) // OK
})

How inject a parameter/service into a Doctrine Entity Listener

I am using Symfony 4 try to inject a parameter into an Doctrine Entity Listener
Konfiguration:
App\EventListener\MyListener:
arguments:
- "%kernel.cache_dir%"
tags:
- { name: doctrine.orm.entity_listener }
Annotation of Entity Class:
#ORM\EntityListeners({"App\EventListener\MyListener"})
Listener:
namespace App\Eventlistener;
use Doctrine\ORM\Event\LifecycleEventArgs;
class MyListener {
private $cacheDirectory;
public function __construct($cacheDirectory)
{
$this->cacheDirectory = $cacheDirectory;
}
public function postUpdate($entity, LifecycleEventArgs $args)
{
...
}
}
When updating the Entity i get the Exception:
Too few arguments to function __construnt().
0 passed in ...\vendor\doctrine\doctrine-bundle\Mapping\ContainerAwareEntityListenerResolver.php on line 76 and exactly 1 expected
I also tried setter injection, but the setter method seems never to be called.
(This is a simplified Demo - I actually will need to inject a service and use it in postUpdate)
Documentation: https://symfony.com/doc/master/bundles/DoctrineBundle/entity-listeners.html (but without DI)
UPDATE: I found this Answer but this is not working with symfony 4.

DryIoc - specifying dependency when using constructor injection

Using DryIoc if I register two implementations of the same contract - how can control which implementation to use when using constructor injection?
I see you can you register with a key or metadata - is it possible (using an attribute?) to control with implementation is injected? Or should I require a collection and figure out the correct implementation in the ctor?
You can specify what dependency to consume in constructor via Made.Of strongly-typed spec, like so:
container.Register<SomeClient>(Made.Of(
() => new SomeClient(Arg.Of<IDep>("service key of impl")));
Here is the related SO answer with more options.
Attributed registration is supported via MEF Attributed Model:
[Export]
public class SomeClient {
public SomeClient([Import("x")]IDep dep) {}
}
[Export("x", typeof(IDep))]
public class X : IDep {}
[Export("y", typeof(IDep))]
public class Y : IDep {}
// in composition root:
using DryIoc.MefAttributedModel;
container = new Container().WithMefAttributedModel();
container.RegisterExports(
typeof(SomeClient),
typeof(X),
typeof(Y));
container.Resolve<SomeClient>(); // will inject X

Can I use an IoC container in unit/integration tests?

I've got an IoC container doing some complicated object construction when resolving some interfaces. I want to use implementations of these interfaces in my unit/integration tests. Is there anything wrong with resolving these interfaces in the tests using the IoC container or is it expected that one should build up instances manually in this situation?
When we are unit testing a class we are concerned with 'does the class do what we want it to do'.
Our starting point is a fully constructed instance; how we got there is not a unit testing question though it may be considered an integration testing question.
Say we have,
A
A(IB b, IC c)
B : IB
B(ID d)
C : IC
D : ID
Where:
IB is an interface for B,
IC is an interface for C, and
ID is an interface for D.
When unit testing A, the fact that B uses ID should be moot (if it is not then we should look at our interfaces. Having A access IB.D.xxx() is not good), all we need to do is provide A with some implementation (mocked/stubbed) of IB and IC.
As far as the unit tests for A are concerned, whether the A instance is created by hand or by a container is not important. We get the same object either way.
As long as we are passing in mocks as the first level dependencies then there is no saving when using a container over creating the object by hand. The saving only happens when we are creating object graphs using the IOC, but if we are doing this then we are into integration testing. This is not necessarily a bad thing but we need to be clear on our goals.
When unit testing the above we create unit testing for
D
C
B (passing in a mocked/stubbed ID)
A (passing in mocked/stubbed IC and IB)
When unit testing A we do not need the correct answer from D to be passed through B up to A.
All we care is that the logic in A works as expected, say, A calls IB.x() with the parameters y and z and returns the result of IB.x(). If we are checking that we get the correct answer (say, one which depends on logic in D) then we are past unit testing and into integration testing.
Bottom Line
It does not matter whether or not the unit under test was created by an IOC container or by hand as long as we are properly isolating the unit under test. If we are using the container to create an object graph then the odds are good that we are into integration testing (and/or have problems with too much coupling between classes - A calling IB.D.xxx())
Mocking for Integration Tests
Caveat: Some of this following is dependent upon the IOC container in use. When using Unity, the last registration 'wins'. I do not know that this holds true for others.
In the minimalist system under question we have
A
A (IB b)
B : IB
B is our 'leaf'. It talks to the outside world (say, reads from a network stream).
When Integration testing, we want to mock this.
For the live system, we set up the ServiceLocator using CreateContainerCore().
This includes the registration of the 'live' implementation of IB.
When executing integration tests that require a mocked version of IB we set up the container using CreateContainerWithMockedExternalDependencies() which wraps CreateContainerCore() and registering a mocked object for IB.
The code below is heavily simplified but the shape extends out to as many classes and dependencies as required. In practice, we have a base test class that aids setting up the service locator, mocking/stubbing classes, accessing the mocks for verification purposes and other house keeping (e.g.so that each test doesn't need to explicitly set the ServiceLocator provider)
[TestClass]
public class IocIntegrationSetupFixture {
[TestMethod]
public void MockedB() {
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(CreateContainerWithMockedExternalDependencies()));
var a = ServiceLocator.Current.GetInstance<A>();
Assert.AreEqual("Mocked B", a.GetMessage());
}
[TestMethod]
public void LiveB() {
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(CreateContainerCore()));
var a = ServiceLocator.Current.GetInstance<A>();
Assert.AreEqual("Live B", a.GetMessage());
}
private IUnityContainer CreateContainerCore() {
var container = new UnityContainer();
container.RegisterType<IB, B>(new ContainerControlledLifetimeManager());
return container;
}
private IUnityContainer CreateContainerWithMockedExternalDependencies() {
var container = CreateContainerCore();
var mockedB = new Mock<IB>();
mockedB.SetupGet(mk => mk.Message).Returns("Mocked B");
container.RegisterInstance<IB>(mockedB.Object);
return container;
}
public class A {
private IB _b;
public A(IB b) {
_b = b;
}
public string GetMessage() {
return _b.Message;
}
}
public interface IB {
string Message { get; }
}
private class B : IB {
public string Message {
get { return "Live B"; }
}
}
}