jmockit - Mocking chain of methods one of which returns a Collection using #Cascading - jmockit

I am trying to mock a method call which goes something like this:
rapContext.getSysInfo().get(key)
The getSysInfo() method returns a ConcurrentHashMap.
Here is what I have done:
Class ABCTest {
#Cascading RapContext context;
#Test
doTest() {
new Expectations() {
{
rapContext.getSysInfo().get(anyString);
result = new UserPrefCtxObject();
}
}
}
With this I get a NullPointerException on rapContext.getSysInfo(). Call to getSysInfo() returns null. If I call any other method which does not return a collection, for instance rapContext.getDomain() everything working fine.
I am not sure what I am missing.
Thanks

The code example is not complete however you are likely running into some issue associated with accidentally mocking Map. If a Map (or any part of the Collection framework) is mocked then a lot of things will break. I could not reproduce your problem as any attempt to mock RapContext using #Cascading resulted in a stack over flow.
You could partially mock RapContext instead and then either return a real or mocked Map. When I run into similar issues I generally get around them using either #Injectable to only mock an instance of a class or using partial mocks.
Here is an approach that will let you mock getSysInfo:
public class RapContextTest {
#Injectable ConcurrentHashMap<String, Object> mockedMap;
#Test
public void testContext() {
RapContext context = new RapContext();
new MockUp<RapContext>(){
#Mock
public ConcurrentHashMap getSysInfo(){
return mockedMap;
}
};
new NonStrictExpectations() {
{
mockedMap.get(anyString);
result = "Success";
}
};
Object value = context.getSysInfo().get("test");
System.out.println(value);
}
}

Related

test objects created inside a method jmockit

The method which I wanted to test looks like:
public void method1(String str) {
ParmaObjectRequest request = new ParmaObjectRequest(str);
this.instanceVar.save(request);
}
I wanted to test if this.instanceVar.save is called with an ParmaObjectRequest object with str value using jmockit.
The test case I have written looks like below and I am able to test that my method is called 1 times but not the parameter inside it.
#Test
public void testMethod1() {
new Expectations() {
{
this.instanceVar.save((ParmaObjectRequest) any);
times = 1;
}
};
testObject.method1("dummyString");
}
But I also wanted to test that this.instanceVar.save is called with object containing "dummyString".
In the Expectations block, change "this.instanceVar" to "testObject.instanceVar"

How do I bind an Interface to automapper using Ninject

I want to use DI whenever I call automapper so that I can uncouple some of my layers. Instead of calling automapper like this:
public class MyController : Controller
{
public ActionResult MyAction(MyModel model)
{
var newModel= Mapper.Map<MyModel, NewModel>(model);
return View(model);
}
}
I want to do this:
public class MyController : Controller
{
IMappingEngine _mappingEngine;
public MyController(IMappingEngine mappingEngine)
{
_mappingEngine = mappingEngine;
}
public ActionResult MyAction(MyModel model)
{
var newModel= _mappingEngine.Map<MyModel, NewModel>(model);
return View(model);
}
}
I am using Ninject as my IOC. How do I bind an interface to it though?
I also need to mention that I am using Profiles and already have:
var profileType = typeof(Profile);
// Get an instance of each Profile in the executing assembly.
var profiles = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => profileType.IsAssignableFrom(t)
&& t.GetConstructor(Type.EmptyTypes) != null)
.Select(Activator.CreateInstance)
.Cast<Profile>();
// Initialize AutoMapper with each instance of the profiles found.
Mapper.Initialize(a => profiles.ForEach(a.AddProfile));
I know that the step I am missing involves binding to the kernal:
kernel.Bind<IMappingEngine>.To<>(); //I do not know what
//to bind it to here so that when I call IMappingEngine;
//It will trigger my maps from my automapper profiles.
I can't seem to find IMappingService in the AutoMapper repository (https://github.com/AutoMapper/AutoMapper/search?q=IMappingService). However, there is a IMappingEngine.
All you've got to do is
IBindingRoot.Bind<IMappingEngine>().ToMethod(x => Mapper.Engine);
or
IBindingRoot.Bind<IMappingEngine>().To<MappingEngine>();
IBindingRoot.Bind<IConfigurationProvider>().ToMethod(x => Mapper.Engine.ConfigurationProvider);
and you're good to go.
Remember, however, that the first access to Mapper.Engine or Mapper.ConfigurationProvider will initialize AutoMapper.
So without the binding, AutoMapper get's initialized the first time you do something like Mapper.Map<,>. With the binding it will get initialized the first time an object is constructed which gets IMappingEngine injected.
If you want to retain the previous initialization behavior there are a few choices:.
a) Instead of injecting IMappingEngine inject Lazy<IMappingEngine> instead (i think this requires the ninject.extensions.factory extension)
b) bind IMappingEngine to a proxy (without target). The proxy should access the Mapper.Engine only when .Intercept(...)ing a method. Also it should forward the method calls.
c) write your own LazyInitializedMappingEngine : IMappingEngine implementation which does nothing than forward every method to Mapper.Engine.
i would probably go with c), the others are too much work. c) will require code adaption whenever the interface of IMappingEngine changes. b) would not but is more complicated and slower. a) is bleeding through to all consumers of the interface and easily to get wrong once in a while, breaking stuff and a bit hard to trace back, so i would refrain from it, too.
c):
public class LazyInitializedMappingEngine : IMappingEngine
{
public IConfigurationProvider ConfigurationProvider { get { return Mapper.Engine.ConfigurationProvider; } }
public TDestination Map<TDestination>(object source)
{
return Mapper.Map<TDestination>(source);
}
public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
return Mapper.Map<TDestination>(source, opts);
}
public TDestination Map<TSource, TDestination>(TSource source)
{
return Mapper.Map<TSource, TDestination>(source);
}
//... and so on ...
}
kernel.Bind<IMappingEngine>().To<LazyInitializedMappingEngine>();

How to force MOXy to use the setter on a Collection property that is lazily initialized?

Given a bean like this:
public class MyBean {
private List<Something> things;
private List<Something> internalGetThings() {
if (things == null) {
things = new ArrayList<Something>();
}
return things;
}
public Iterable<Something> getThings() {
return <an immutable copy of internalGetThings()>;
}
public void setThings(List<Something> someThings) {
things.clear();
for (Something aThing : someThings) {
addThing(aThing);
}
}
public void addThing(Something aThing) {
things.add(aThing);
// Do some special stuff to aThing
}
}
Using external mapping file, when I map like this:
<xml-element java-attribute="things" name="thing" type="com.myco.Something" container-type="java.util.ArrayList" />
It seems that each individual Something is being added to the MyBean by calling getThings().add(). That's a problem because getThings() returns an immutable copy of the list, which is lazily initialized. How can I configure mapping (I'm using an external mapping file, not annotations) so that MOXy uses setThings() or addThing() instead?
Why Does JAXB/MOXy Check the Get Method for Collection First?
JAXB (JSR-222) implementations give you a chance to have your property be the List interface and still leverage the underlying List implementation that you choose to use. To accomplish this a JAXB implementation will call the get method to see if the List implementation has been initialized. It it has the List will be populated using the add method.
public List<String> getThings() {
if(null == things) {
things = new ArrayList<String>();
}
return things;
}
public List<String> getThings() {
if(null == things) {
things = new LinkedList<String>();
}
return things;
}
If you don't pre-initialize the List property then MOXy/JAXB will build an instance of the List (default is ArrayList) and set it on the object using the set method.
private List<Something> things; // Don't Initialize
public List<String> getThings() {
return things;
}
public void setThings(List<String> things) {
this.things = things;
}
Given the reason in #Blaise's answer, it doesn't seem possible to have MOXy (or any JAXB implementation in general?) populate a lazily-initialized collection via a setter method on the collection. However, a combination of xml-accessor-type="FIELD" (or #XmlAccessorType if using annotations) and defining a JAXB unmarshal event callback will get the job done. In my afterUnmarshal() implementation I do the special work on Something instances that is done in addSomething().
private void afterUnmarshal(Unmarshaller, Object parent) {
for (Something aThing : getSomethings()) {
// Do special stuff on aThing
}
}
Using FIELD access type gets JAXB/MOXy to directly inject the collection into the field, bypassing the getter. Then the call back cleans things up properly.

Rhino.Mocks how to test abstract class method calls

I'm trying to test if the method I want to test calls some external (mock) object properly.
Here is the sample code:
using System;
using Rhino.Mocks;
using NUnit.Framework;
namespace RhinoTests
{
public abstract class BaseWorker
{
public abstract int DoWork(string data);
}
public class MyClass
{
private BaseWorker worker;
public BaseWorker Worker
{
get { return this.worker; }
}
public MyClass(BaseWorker worker)
{
this.worker = worker;
}
public int MethodToTest(string data)
{
return this.Worker.DoWork(data);
}
}
[TestFixture]
public class RhinoTest
{
[Test]
public void TestMyMethod()
{
BaseWorker mock = MockRepository.GenerateMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
mock.GetMockRepository().ReplayAll();
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
}
When I run this test, I get:
TestCase 'RhinoTests.RhinoTest.TestMyMethod'
failed: System.InvalidOperationException : Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.Expect.Call[T](T ignored)
RhinoTest.cs(48,0): at RhinoTests.RhinoTest.TestMyMethod()
The exception is thrown on the Expect.Call line, before any invocation is made.
How do I approach this - i.e. how to check if the method under test properly forwards the call?
This is .Net 2.0 project (I can no change this for now), so no "x =>" syntax :(
I have to admit, I'm not entirely sure what's going on here, but using Rhino.Mocks 3.6 and the newer syntax, it works fine for me:
[Test]
public void TestMyMethod()
{
MockRepository mocks = new MockRepository();
BaseWorker mock = mocks.StrictMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
using (mocks.Record())
{
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
}
using (mocks.Playback())
{
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
It doesn't have anything to do with the Rhino.Mocks version. With the old syntax, I get the same error as you're getting. I didn't spot any obvious errors in your code, but then again, I'm used to this using syntax.
Edit: removed the var keyword, since you're using .NET 2.0.

Testing In A Try Catch With Moq Compared To Rhino Mocks

I've just been working on some tests using Moq but ran into trouble trying to test a method I wanted to call twice through a try catch block. The principle is that the first call throws an exception, then in the catch I correct the problem and call the method again.
I managed to do it with Rhino Mocks as below but being new to both frameworks I wondered if anyone could tell me if the same can be achieved using Moq.
// C.U.T
public class Mockee
{
bool theCatLives = true;
public Mockee() { }
public virtual void SetFalse()
{
theCatLives = false;
}
}
[Test]
public void TestTryCatch(){
var mr = new MockRepository();
var mock = mr.StrictMock<Mockee>();
mr.Record();
Expect.Call(mock.SetFalse).Throw(new Exception());
Expect.Call(mock.SetFalse);
mr.ReplayAll();
try
{
mock.SetFalse();
}
catch
{
mock.SetFalse();
}
mock.VerifyAllExpectations();
}
This isn't particularly easy to do with Moq, as it has no concept of ordered expectations. You can, however, use the Callback method and throw exceptions from there, like this:
var actions = new Queue<Action>(new Action[]
{
() => { throw new Exception(); },
() => { }
});
var mock = new Mock<Mockee>();
mock.Setup(m => m.SetFalse()).Callback(() => actions.Dequeue()()).Verifiable();
try
{
mock.Object.SetFalse();
}
catch
{
mock.Object.SetFalse();
}
mock.Verify();
However, one caveat is that this version only checks whether the SetFalse method was called at all.
If you want to verify that it was called twice, you can change the last statement to this:
mock.Verify(m => m.SetFalse(), Times.Exactly(2));
However, this slightly violates the DRY principle because you would be stating the same Setup twice, but you could get around that by first declaring and defining a variable of type Expression<Action<Mockee>> and use it for both the Setup and the Verify methods...