Unit testing a lambda function in Java - java

I have a lambda function written like this:
#Bean
public Function<Request, Audience>
fromAudienceDTOToAudienceMapper(
final Function<ExpressionDto, Expression> fromExpressionDtoToExpression,
final Function<SchemaDto, Schema> fromSchemaDtoToSchema,
final Function<PolicyDTO, Policy>
fromDataGovernancePolicyDtoToDataGovernancePolicy
)
As this is a bean and a lambda function, I am unable to come up with a way using Junit/Mockito to actually test this out. If I instantiate the function, it will have its own apply() and then the original code will not get called.
I'm inclining towards converting this to a class itself, but thought of finding a way to unit test this out directly. Any help is appreciated!

Related

Return class from method in mocked method. Mockito

I have class TaskType. It has method
public Class<? extends TaskParameters> getTypeParameters() {
return typeParameters;
}
next i want to mock this class and mock this method:
final TaskType TEST_PARAMETERS = Mockito.mock(TaskType.class);
when(TEST_PARAMETERS.getTypeParameters()).thenReturn(ScheduledParameters.class);
Mockito.doReturn(4).when(TEST_PARAMETERS).ordinal();
but i got problem:
error: no suitable method found for thenReturn(java.lang.Class<com.ucp.shard.bulkops.service.executor.ScheduleExecutorTest.ScheduledParameters>)
when(TEST_PARAMETERS.getTypeParameters()).thenReturn(ScheduledParameters.class);
Help, how can i mock this method?
Your question is missing a lot of information, it would be nice if you could update it. For example, you could share the code for TaskType.
First of all, it seems that TaskType is an enum as you are trying to call ordinal(), right? If it's the case, you need to remember that enums are final and cannot be mocked by Mockito by default (please read here for more information). If it's not an enum you can ignore it. :)
Regarding the problem mocking getTypeParameters(), you cannot do it directly due to type erasure (more information here). However, you can solve it using Mockito Answer:
final TaskType TEST_PARAMETERS = Mockito.mock(TaskType.class);
final Answer<Class<ScheduledParameters>> answer = invocation -> ScheduledParameters.class;
when(TEST_PARAMETERS.getTypeParameters())
.thenAnswer(answer);
Mockito.doReturn(4).when(TEST_PARAMETERS).ordinal();

How to mock private enum using Powermock?

I have following class:
public class MyClazz
{
private static enum MyEnum
{
INSTANCE;
private MyClazzB getMyClazzB()
{
....
return
}
final MyClazzB b = getMyClazzB();
}
public void methodWhichIWantTest(arguments)
{
//...
//here is logic which I want to test
//...
MyEnum.INSTANCE.b.doSomething();//I want to mock this line.
}
}
I am not author of MyClazz and I do not want to change anything. I only want to test methodWhichIWantTest method. The problem is that method getMyClazzB throws exception. I do not how to mock it.
How to mock it? I think that I should mock MyEnum class but it is private.
===EDIT===
I think that I should clarify my question because I got some comments.
I am not author of MyClazz but this class is part of my project and I can edit this class but I would like to avoid editing as much as possible. I fixed some bug in private method of MyClazz. I would like to write some test which tests my fix. Testing private method is not good practice so I can write integration test or write unit test for some public method which calls this private method. Firstly I wanted to write integration test but after research I found that integration test is to complicated and takes me too much time. So I decided to write unit test for some public method which calls this private method. methodWhichIWantTest is this public method. Method getMyClazzB throws exception because it crates javax.naming.InitialContext and lookup some beans (It works properly on wildfly but it does not work inside simple unit test).
I think that I have following options:
do not test it
write integration test (it is time consuming)
try to mock MyEnum and write unit test
try to mock InitialContext and write unit test
edit source code, mock and write unit test.
test private method directly using java reflection
My question is related to point 3. I do not know how to realize point 3 I was curious how to do it so I asked my question.
I am afraid that realizing point 3 is not possible within a reasonable time.
Thank you for help.
how-to-mock-an-enum-singleton-class-using-mockito-powermock does not solve my issue because MyEnum enum is a private. E.g. I cannot use #PrepareForTest({MyEnum.class}) annotation because MyEnum is not accessible.

How scala implicit make abstract method valid parameter so I can use method in java

So this is a bit of a strange question, but I am trying to make use of a piece of code that is in scala and takes a set of parameters. In scala the parameters are implicits so scala is able to do its magic to fill in what those objects need. But since I can't make an abstract object be "implicit" in java, I need to figure out how to create the object, but can't for the life of me.
Here is the scala code:
class AsyncSchemaRegistryClient (
val baseUri: String
) (
implicit as: ActorSystem,
m: Materializer,
ec: ExecutionContext
) extends SchemaRegistryClient[Future] with Json4sSupport {...
So this is called by another method in original code (in a long twisty path of Guice Inject and sub modules that is hard enough to follow as is), and I am trying to call it in the java code like this:
private AsyncSchemaRegistryClient asyncSchemaRegistryClient = new AsyncSchemaRegistryClient("test", ActorSystem.create(), Materializer(), new ExecutionContext);
Now the ActorSystem.create() seems to be valid (at least the compiler isn't yelling about it), but the Materializer and the ExecutionContext I cannot initialize because the are abstract. Also it is worth saying that the Materializer is akka.stream.Materializer and ExecutionContext is scala.concurrent.ExecutionContext.
The reason I am trying to make use of this AsyncSchemaRegistryClient is that it has a lot of code already set up for properly calling a schema registry and handling if it comes back with valid schema data or not and seems to be the easiest way to implement async checks on schema in my program.
Thanks in advance for any and all advice!
Try
ActorSystem system = ActorSystem.create();
ExecutionContextExecutor ec = system.dispatcher();
ActorMaterializer mat = ActorMaterializer.create(system);
new AsyncSchemaRegistryClient("test", system, mat, ec);

Spock bug with testing private method?

Can somebody tell me if this is a bug or intended behavior.
I know in Spock I can test private methods:
def "test with private"() {
given:
FileContentValidator fileContentValidator = new FileContentValidator(1)
when:
fileContentValidator.validateCustomerSiteId("") // this is a private method
then:
true // succeeds
}
But when I try the same thing using a Spock Spy, it fails:
def "test with private on spy"() {
given:
FileContentValidator fileContentValidator = Spy(FileContentValidator, constructorArgs: [1])
when:
fileContentValidator.validateCustomerSiteId("") // this is a private method
then:
true // does not get here
}
I get an exception:
groovy.lang.MissingMethodException: No signature of method: com.shoppertrak.device.management.web.validator.ophour.FileContentValidator$$EnhancerByCGLIB$$7ff6a42.validateCustomerSiteId() is applicable for argument types: (java.lang.String) values: []
I think this is due to how the cglib works. When testing an existing concrete class, Spock doesn't get involved in the byte code, so you're taking advantage of a flaw in Groovy that give you access to private methods. When you spy or mock the same class, the Spock/cglib manipulation steps in and changes the resulting byte code. The end product is a method that is truly private, thus you can't access it.
There are probably hacks you can use to get around it, but you're probably better off adding something like a CustomerSiteIdValidator class with a public validateCustomerSiteId() that gets injected into your FileContentValidator class. Then you can easily mock it and isolate responsibilities.
Someone suggested adding the ability to Spy private methods, but the ticket was closed as Won't Fix
https://github.com/spockframework/spock/issues/403

How do I use a Java-defined instance method in Lua?

I'm aware that it is possible to use Java defined static methods in Lua, due to the section "Libraries of Java Functions" on http://luaj.org/luaj/README.html.
However I am struggling to find out how I can use the same for instance methods, I have a shortened example here:
private static class CallbackStore {
public void test(final String test) {
}
}
(I am aware that I can use a static method here as well, but it is not possible with the real life scenario)
I am using the following Lua code:
-- Always name this function "initCallbacks"
function initCallbacks(callbackStore)
callbackStore.test("test")
end
Which does not work as it is expecting userdata back, but I give it a string.
And I call the Lua code like this:
globals.load(new StringReader(codeTextArea.getText()), "interopTest").call();
CallbackStore callbackStore = new CallbackStore();
LuaValue initCallbacks = globals.get("initCallbacks");
initCallbacks.invoke(CoerceJavaToLua.coerce(callbackStore));
where the Lua code is returned by codeTextArea.getText()
Bottom line of my question is, how do I make my code running with test as an instance method?
When accessing member functions (in Lua objects in general, not just luaj) you have to provide the this argument manually as the first argument like so:
callbackStore.test(callbackStore,"test")
Or, you can use the shorthand notation for the same thing:
callbackStore:test("test")

Categories

Resources