Any() method fails to compile in Java 1.8 with Mockito 1.10.9 - junit

My below code works well with Java 1.7 and Mockito version is 1.10.19.
#Test
public void populateUsersEmpty() {
// arrange
List<UserDTO> users = new ArrayList<UserDTO>();
// act
requestBuilder.populateUsers(mxsMessageOutMock, users);
// assert
verify(mxsMessageOutMock, times(0)).addRecordSet(CreateNewAlertRequestBuilder.MXS_RECORDSETNAME_USERS);
verify(mxsMessageOutMock, times(0)).addFieldNewRecord(anyString(), anyString());
verify(mxsMessageOutMock, times(0)).addField(anyString(), any());
}
But when I moved to Java 1.8 with same version of Mockito it started showing below error (bold letters). When I checked Mockito website I found that Mockito 3 yet to support java 8. If yes,then what is solution for this? Should I have to wait for their release or Is there any way to fix this. I tried passing AnyString() in place of any() but my code breaks still. Even anyObject() didn't help me.
verify(mxsMessageOutMock, times(0)).addField(anyString(), anyString());
CreateNewAlertRequestBuilderTest.java:436:0::0 The method addField(String, String) is ambiguous for the type IMXSMessageOut
[ant:iajc] [error 7]: error at verify(mockMessageOut, times(0)).addField(anyString(), any());
I understand that Its difficult to suggest without full code but here what I could share piece of code.

any(String.class)? if addField is accepting String, String why don't u use anyString(), anyString()

Related

Unexpected behaviour from Gson

I developed a small application that stores data coming from a device: I chose to store data in JSON format, and the serialization/deserialization of the data works just fine, even if it involves some custom types created by me...but only I work in the IDE (Eclipse, for that matter).
When I export a runnable JAR file though, the deserialization of the data encounters some kind of problem, because the software always throws this exception:
Caused by: java.lang.UnsupportedOperationException: Cannot allocate class LocalDateTime
at com.google.gson.internal.UnsafeAllocator$4.newInstance(UnsafeAllocator.java:104)
at com.google.gson.internal.ConstructorConstructor$14.construct(ConstructorConstructor.java:225)
... 88 common frames omitted
I thought I'd encounter problems with custom types, not a built-in one. At this point, I discovered two things:
if I use a full JRE 9 to run the JAR file, the exception is not thrown: I double checked the modules included in the custom JRE I created with Jlink.exe, and everything is included correctly. I still want to use a smaller JRE, so I did not investigate further yet (I guess this explains why in the IDE it works perfectly)
I added a custom deserializer to the Gson object (see below), with which I simply manually converted the JSON string into a valid data, and that avoided the exception on the LocalDateTime class...but the exception reappeared simply on another class, this time a custom-made one.
At this point, I guess I can simply add a deserializer for each data type that causes problem, but I'm wondering why the issue won't happen with a full JRE, and why a smaller JRE causes this, even if all the modules required are included. Maybe it's worth mentioning also that I added no custom serializer to the Gson object that saves the data, it is all serialized as per Gson default.
LocalDateTime deserializer:
#Override
public LocalDateTime deserialize(JsonElement json, java.lang.reflect.Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject joDate = json.getAsJsonObject().get("date").getAsJsonObject();
JsonObject joTime = json.getAsJsonObject().get("time").getAsJsonObject();
//JSON example: {"date":{"year":2019,"month":1,"day":9},"time":{"hour":6,"minute":14,"second":1,"nano":0}
return LocalDateTime.of(joDate.get("year").getAsInt(),
joDate.get("month").getAsInt(),
joDate.get("day").getAsInt(),
joTime.get("hour").getAsInt(),
joTime.get("minute").getAsInt(),
joTime.get("second").getAsInt(),
joTime.get("nano").getAsInt());
}
}
Jdeps.deps modules list:
com.google.gson
java.base
javafx.base
javafx.controls
javafx.fxml
javafx.graphics
org.slf4j
After the answer I received, I opened an issue here.
TL;DR
You need a runtime image (e.g. full JDK or something built with jlink) that includes the module jdk.unsupported.
Full Answer
GSON wants to create instances of classes it deserializes without calling any constructors (so nothing gets initialized without GSON saying so). This can't normally be done, but sun.misc.Unsafe offers a way to do this with the method allocateInstance. To that end, GSON needs an instance of sun.misc.Unsafe. The topmost frame in the call stack is from UnsafeAllocator, which uses common trickery to get Unsafe.
The problem is, sun.misc.Unsafe is in module jdk.unsupported, which is present in a full JDK but you won't usually find in runtime images.
When creating your runtime image with jlink, make sure to include the option --add-modules jdk.unsupported and you should be good to go.
Arguably, GSON should declare an optional dependency on jdk.unsupported with requires static.
I have faced the same issue when packing compose a desktop application.
update build.gradle file, add an unsupported module.
compose.desktop {
application {
mainClass = "MainKt"
nativeDistributions {
targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
packageName = "admin"
packageVersion = "1.0.0"
modules("java.sql")
modules("jdk.unsupported")
}
}
}

ASP.NET 5: Configuring IdentityServer3 authentication

I've just started digging into the new ASP.NET 5 by creating a test single page application with the OAuth login. I already know that I can use IdentityServer3 for that purpose and it seems pretty nice. I've found a post by Dominick Baier which is explaining how to set up the IdentityServer3. However, the post seems to be out of date or the identity server itself isn't working with the latest version of the ASP.NET 5 (which is beta7 at the moment).
The problem is, when I try to configure the IdentityServer in the Startup.cs I got an error from VS telling me that IApplicationBuilder has no extension method called UseIdentityServer. And this seems to be true, since in the IdentityServer3 source code they have this extension method declared for IAppBuilder (not IApplicationBuilder).
Here is my code (Startup.cs):
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Add MVC to the request pipeline.
app.UseMvc();
var options = new IdentityServerOptions
{
Factory = new IdentityServerServiceFactory()
};
app.UseIdentityServer(options);
}
And the error (on the last line) is
'IApplicationBuilder' does not contain a definition for 'UseIdentityServer' and the best extension method overload 'UseIdentityServerExtension.UseIdentityServer(IAppBuilder, IdentityServerOptions)' requires a receiver of type 'IAppBuilder'
Obviously, if I change the parameter type in the Configure method to IAppBuiler, it'll throw a runtime error because the dependency injection will not be able to inject that type. Even if it would, I'd lose the UseMvc() extension method.
So could you point me in the right direction please?
Perhaps I'm just missing something tiny but crucial here.
Thanks in advance!

Castle Windsor IInterceptor Configuration (Nancy bug)

So I ran into this issue with the Windsor bootstrapper for Nancy. I managed to whip together a small test project where I can reproduce what is going wrong. You can find the project here.
What seems to go wrong is this: DynamicProxy only seems to catch the invocation of the void Handle(Action<string> oncomplete) method and not the string Handle(string input) method that is called on another thread. As if the Engine is no longer proxied after it had been sent to another thread. Scratch that: It's just the call to another method on the same class that is not proxied.
This means the output of the program is only
Handled Handle with return type System.Void
test
and not
Handled Handle with return type System.Void
Handled Handle with return type System.String
test
Is this the expected behaviour of Dynamic Proxy? That proxies on another thread are not longer, well, proxied? Or is there something wrong with the code?
EDIT: Just RTFM'd Dynamic Proxy, and it seems like it Works As Intended. Now how do I configure my IEngine Instance to use the correct kind of Proxy?
Try changing :
Component.For<MyEngine>().Forward<IEngine>().Interceptors<ScopeInterceptor>());
into
Component.For<MyEngine>().Forward<IEngine>().Forward<MyEngine>().Interceptors<ScopeInterceptor>());
I don't have the time to actually try it but this should force windsor into creating a class proxy, which should solve your issue
Kind regards,
Marwijn.
-- edit --
for the current link try replacing :
Component.For<IEngine>().ImplementedBy<Engine>()
with:
Component.For<IEngine, Engine>().ImplementedBy<Engine>()

How to jmock Final class

I was trying to mock final class(AnyFinalClass.java) in junit using JDave in eclipse.
public void setUp() throws Exception {
Mockery mockery = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
AnyFinalClass any = mockery.mock(AnyFinalClass.class);
}
I am trying to use jdave-unfinalizer-1.1.jar as javaagent but didnt had any success. I tried multiple things but getting following exception
java.lang.IllegalArgumentException: Cannot subclass final class class AnyFinalClass
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
Can someone who has already tried jdave unfinalizer give me exact step how to make it work on eclipse.
I set following in eclipse.ini file but got the problem
-Xbootclasspath/a:lC:\WS\JunitTesting\jars\asm-3.0.jar
-javaagent:C:\WS\JunitTesting\jars\jdave-unfinalizer-1.1.jar
While running executing the junit, I gave vm argument as
javaagent:C:\WS\JunitTesting\jars\jdave-unfinalizer-1.1.jar
I am not sure what will be the code. jdave is not having the code and its site is pointing to some other site which is not working. Please correct my code or provide your same working code.
Any help is highly appreciated.
from Enhancer.java line 446:
if (TypeUtils.isFinal(sc.getModifiers()))
throw new IllegalArgumentException("Cannot subclass final class " + sc);
I have not worked with JDave but with another mocking frameworks and the only one that allows to mock a final class was powermock
Look also here
In order to get unfinalizer running you have to put -javaagent:path_to_unfinalizer/jdave-unfinalizer-1.1.jar in the VM arguments of the run configuration of the test.
I also had to include several dependencies of jdave-unfinalizer in the classpath of the project from which the tests ar being launched. These are, taken from the maven definitions of jdave:
jdave-core 1.1
cglib-nodep 2.1_3
objenesis 1.0
asm 3.0
asm-commons 3.0
asm-tree 3.0

PowerMokito issue with extended methods

Issue: Cannot stub a method on a return object from an extended class.I just get null pointers on the method I am trying to stub. Do I need to perform a spy first on the objects? I tried that as well and didn't work.
Test Framework:
PowerMockito version 1.9
PowerMock version 1.4.11
EasyMock version 3.1
Line of code attempting to test.
String expected = methodFromExtendedClass_GetObject().getStringValueFromReturnObject();
Test Code
PowerMockito.stub(MemberModifier.method(ExtendedClassA.class, "methodFromExtendedClass_GetObject()")).toReturn(new testObject());
PowerMockito.stub(MemberModifier.method(testObject.class, "getStringValueFromReturnObject")).toReturn(testString);
I dont know the EasyMock syntax, but I do know Mockito. I dont have too much to work with here, but it seems that you are just trying to create a Stubbed Object to return another Mock that returns a string.
If so, Create the Mock test object:
TestObject testObject = mock(TestObject.class);
when(testObject.getStringValueFromReturnObject()).thenReturn(testString);
Then use that Mock as the return for your stub:
PowerMockito.stub(MemberModifier.method(ExtendedClassA.class,
"methodFromExtendedClass_GetObject()")).toReturn(testObject);