How to mock Object Mapper - testing

abp.io framework - testing
I am trying to set an ApplicationService class.
The method I'm trying to test uses 'ObjectMapper.Map<classFrom, classTo>(obj)'
I have used NSubstitue as LazyServiceProvider, but I am unable to find the correct Substitute to create an ObjectMapper.
Has anyone done this?

We resolved the issue.
We used a substitute for LazyServiceProvider.
Then the key was using a very specific setup when the LazyServiceProvider is trying to create the Object Mapper (see the abp code).
_abpProvider = Substitute.For<IAbpLazyServiceProvider>();
_abpProvider.LazyGetService<IObjectMapper>(Arg.Any<Func<IServiceProvider, object>>()).Returns(_objectMapper);
This allowed us to set up our own ObjectMapper in our test method, and have it be used in our ApplicationService.

Related

How to Mock private variable in Grails in spock framework

My objective is to Mock the private variable in method of a service class in Grails.
Here I tried bellow way in my test method:
given: 'Mocking of object'
def dataSource = Mock(TransactionAwareDataSourceProxy)
def db1 = Mock(Sql)
service.dataSource = dataSource
new Sql(dataSource) >> db1
List<GroovyRowResult> resultList = new ArrayList<>()
GroovyRowResult result = new GroovyRowResult(id: 0)
result.someAmount = 400
resultList.add(result)
db1.rows(_) >> resultList
In my service class my code is :
def db = new Sql(dataSource)
List<GroovyRowResult> resultList = db.rows("Select * from user_info")
Here, I successfully mocked the TransactionAwareDataSourceProxy named dataSource but I am failed to assign mock def db = new Sql(dataSource) into local private variable db.
I need bellow solution:
How to mock the private variable inside a method. Here, I am assigning Sql in private variable db in my service method
Thanks in advance
The simple answer is: You don't. Instead you refactor to be able to use dependency injection, i.e. pass the Sql instance into the method or into the class. Then you can easily mock it.
See also here and in the other answers linked off of that answer.
The "don't do this at home, kids" part which I do not recommend because it only works for Groovy classes under test and also helps establish bad design in your application code: You can use Spock's Groovy mocks in order to mock constructors. You could achieve the same for Java classes using Mockito, Powermock or my own tool Sarek. Sarek even works for JRE bootstrap classes, also final ones.
But whenever you need Groovy mocks or special add-on tools while writing Spock tests, it is usually a sign you should refactor instead. Only in rare cases where you need to mock something in third party code you are unable to modify, you might need such tools. But even then you can usually refactor your own code in order to access the third party code in such a way that you can inject the right kind of test double (mock, stub, spy) preconfigured to behave like you need it to.

mule endpoint builder from java code

The below code fetches the global endpoint named SomeInbound and is stored in an invocation variable named someUrl
<set-variable variableName="someUrl" value="#[app.registry['SomeInbound'].getEndpointBuilder().getEndpoint().getUri()]"/>
How can we do the same thing in java(how to get that app object in java and also the other methods following that)
'app' is just a MEL specific context object for accessing parts of the MuleContext etc. In Java you can grab the registry from the MuleContext like so: muleContext.getRegistry() and then use one of the lookup methods to get the object you want.
TO get the muleCOntext, there any many possible ways. Some of which are:
From a test case.
Injection or the #Lookup
annotation:http://www.mulesoft.org/documentation/display/current/Lookup+Annotation
Implementing MuleContextAware:
https://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/context/MuleContextAware.html
Or if you're using a Callable component etc. you can get it from the
MuleEventContext : https://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MuleEventContext.html#getMuleContext()

wsdl2java code generation for lists of custom objects

I would like to know if the tool "wsdl2java" (Axis2) is able to generate stubs that support getting list of custom ojects.
For instance, if I have a WS that have the following method:
public List<Device> getDevices(){
//...
}
Where Device is a custom class...
This tool can do that?
I changed the return data type of my Web Service to an array because of that:
http://www.ibm.com/developerworks/webservices/library/ws-tip-coding/index.html
And I had to do some changes (some namespaces) to the generated stub (I used ADB)...
I changed that because it was giving me an ADBException: Unexpected subelement ...

How can you use SessionAsSigner in a Java Bean called from an XPage?

According to Phillip Riand (see: discussion on openNTF) this is not possible... They need to know the design element to find out who signed it. Therefore, it is only available in SSJS.
There are 2 ways that I know of to use the sessionAsSigner object in Java beans:
1 By resolving the sessionAsSigner object:
FacesContext context = FacesContext.getCurrentInstance();
Session sessionAsSigner = context.getApplication().getVariableResolver().
resolveVariable(context, "sessionAsSigner");
2 By using the getCurrentSessionAsSigner() function from the com.ibm.xsp.extlib.util.ExtLibUtil class in the Extension Library.
To be able to use it (in Java as wel as SSJS) you'll want to make sure that all design elements were signed by the same user ID. If that's not the case, the sessionAsSigner object will not be available ('undefined').
I found that the solution is right at hand :-)
I changed my XPage (in this example an XAgent) to:
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" rendered="false">
This is an xAgent returning json data...
<xp:this.afterRenderResponse><![CDATA[#{javascript:Controller.verify(sessionAsSigner)}]]></xp:this.afterRenderResponse>
and in the bean I simply used the session in the argument when I needed to open a database/document as signer. Sometimes the solution is so simple :-)
/John
This is quite an old post that I just stumbled upon. Tried some of the solutions mentioned above:
resolveVariable did not work for me, at least not for sessionAsSigner as this throws a runtime error (I can resolve plain old session, though...)
to be honest I didn't quite understand the Controller.verify(sessionAsSigner) method; is Controller something specific to XAgents? If so, I don't have an XAgent here, so can't use it
didn't feel like importing extra ExtLib classes here...
So I came up with another solution that appears to be very simple:
created a method in my javaBean that takes a session object as argument; since sessionAsSigner belongs to the same class as session I don't have to import something new.
Javacode is:
public void testSession(Session s) throws Exception{
System.out.println(" > test effective user for this session = "
+ s.getEffectiveUserName());
}
This is called from SSJS as either
mybean.testSession(session);
or
myBean.testSession(sessionAsSigner);
Maybe helps others, too

How do I utilize a named instance within the ObjectFactory.Initialize call for StructureMap?

I am trying to do the following bootstrapping:
x.For(Of IErrorLogger).Use(Of ErrorLogger.SQLErrorLogger)().
Ctor(Of IErrorLogger)("backupErrorLogger").Is(ObjectFactory.GetNamedInstance(Of IErrorLogger)("Disk"))
x.For(Of IErrorLogger).Add(
Function()
Return New ErrorLogger.DiskErrorLogger(
CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))
End Function).Named("Disk")
But it shows this error:
StructureMap Exception Code: 200
Could not find an Instance named "Disk" for PluginType Logging.IErrorLogger
I sort of understand why this is happening.. the question is, how do I utilize a named instance within the registry? Maybe something like lazy initialization for the ctor argument for the SQLErrorLogger? I am not sure how to make it happen.
Thanks in advance for any help you can provide.
I found the correct way to do it in the latest version (2.6.1) of StructureMap:
x.For(Of IErrorLogger).Use(Of ErrorLogger.SQLErrorLogger)().
Ctor(Of IErrorLogger)("backupErrorLogger").Is(
Function(c) c.ConstructedBy(Function() ObjectFactory.GetNamedInstance(Of IErrorLogger)("Disk"))
)
x.For(Of IErrorLogger).Add(Function() _
New ErrorLogger.DiskErrorLogger(
CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))
).Named("Disk")
Notice for the Is method of Ctor, we need to provide a func(IContext), and use the IContext.ConstructedBy(Func()) to call ObjectFactory.Get... to successfully register the IErrorLogger in this case.
This is the only way to do it as far as I know. The other Icontext methods such as IsThis and Instance will only work with already registered type.
Your problem is that you are trying to access the Container before it's configured. In order to make structuremap evaluate the object resolution after the configuration you need to provide a lambda to the Is function. The lambda will be evaluated when trying to resolve the type registered.
x.[For](Of ILogger)().Add(Of SqlLogger)().Ctor(Of ILogger)("backupErrorLogger")_
.[Is](Function(context) context.GetInstance(Of ILogger)("Disk"))
x.[For](Of ILogger)().Add(Of DiskLogger)().Ctor(Of String)("errorFileName")_
.[Is](CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))_
.Named("Disk")
Disclaimer: I'm not completely up-to-date with the lambda syntax in VB.NET, but I hope I got it right.
Edit:
The working C# version of this I tried myself before posting was this:
ObjectFactory.Initialize(i =>
{
i.For<ILogger>().Add<SqlLogger>()
.Ctor<ILogger>("backup").Is(
c => c.GetInstance<ILogger>("disk"))
.Named("sql");
i.For<ILogger>().Add<DiskLogger>().Named("disk");
});
var logger = ObjectFactory.GetNamedInstance<ILogger>("sql");