How to match 'any' parameter type while mocking private method in Jmockit - jmockit

I have a problem while using jmockit for the following scenario. Did a research on the web, but couldn't locate the answers yet.
In the record phase, I am setting the expectation on an object that is partially mocked. While doing it, I would like to mock a private method with single parameter. But i don't really concerned with that parameter value. I want to match all invocation of that particular private method with any instance of argument passed to it. How do I do it in Jmockit. Is there a way?
new Expectations(student) {
{
Deencapsulation.invoke(student, "setDepartment", (Department) any);
result = new Delegate<Student>() {
public void setDepartment(Department dept) {
System.out.println("Mocked setDepartment() methodd.....");
}
};
}
};
In the above code, (Department) any can not be passed, since Deencapsulation.invoke(...) method doesn't accept null value.

Note the API documentation for the any field says:
"In invocations to non-accessible methods or constructors (for example, with Deencapsulation.invoke(Object, String, Object...)), use withAny(T) instead."
That is, you need to use withAny(Department.class) with the invoke(...) call.

As of JMockit v1.49, I use:
withInstanceOf(Department.class)
It works as expected.

Related

Pass parameters to Junit 5 TestRunner extension

Trying to figure out how to pass some parameters to my custom implementation of TestWatcher in Junit5. The base class for all tests is set to #ExtendWith with the TestWatcher. Trying to keep it as simple as possible and I can't seem to find a straightforward answer on how to do this
I was struggling on a similar problem, basically I needed a global parameter (a separator string data) for the annotation #DisplayNameGenerator().
Because the lack of code examples of how you're trying to resolve this I'm gonna explain my approach of how to get a parameter provided by the user and see if it works for you,
I created a interface with the return of the String value that is my custom parameter that I wanted to get from the user,
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Inherited
#API(status = EXPERIMENTAL, since = "5.4")
public #interface IndicativeSentencesSeparator {
String value();
}
So this way I could create my test with this new interface, and passing the parameter but also making it optional to use, like this,
#DisplayName("My Test")
#DisplayNameGeneration(DisplayNameGenerator.IndicativeSentencesGenerator.class)
#IndicativeSentencesSeparator(" --> ")
class MyTestClass { //Some test methods and stuff }
To get the this new class in the implementation, I used the java method class.getAnnotation(classType) in the class that you're trying to extract the value, sending by parameter the class to find, in this case the interface I created.
IndicativeSentencesSeparator separator =
myTestClass.getAnnotation(IndicativeSentencesSeparator.class);
And finally to get the parameter used the getter value,
String parameter = separator.value();

How can I pass property getter as a function type to another function

How can I pass property getter to a function that accepts function type?
Here is an example of what I want achieve:
class Test {
val test: String
get() = "lol"
fun testFun(func: ()->String) {
// invoke it here
}
fun callTest() {
testFun(test::get)
// error: Type mismatch: inferred type is
// KFunction1<#ParameterName Int, Char> but () -> String was expected
}
}
Is there a way?
You can reference the getter by writing ::test (or this::test).
When you write test::get, you are actually referencing the get method on String. That method takes an index and returns the character at that index.
If the property was a var and you want a reference to its setter, you can write ::test::set.
For more info on property references, see here: https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11
As already mentioned, you can use this::test to refer to the getter. Alternatively, if you have kotlin-reflect, you can do this::test.getter.
When you pass the field as a function, it assumes you mean the getter. As a result, if you want the setter, you have two options:
this::test::set
or
this::test.setter
The latter, just like this::test.getter requires kotlin-reflect, or the program will crash (tested locally with Kotlin 1.2.50)
You can, however, get the getter in another way. But I recommend you just stick with this::test because it's shorter.
You can do:
this::something::get
With just something::get it refers to the method inside the String class, which returns a char at an index. For reference, the method declaration:
public override fun get(index: Int): Char
If you don't mind, just use { test } (e.g. testFun { test }). This will exactly translate to your () -> String. The next best alternative is probably ::test (or this::test) as was already mentioned.
The second has probably only minor (negligible?) impact on performance. I did not test it myself, nor did I found any source which tells something regarding it. The reason why I say this, is how the byte code underneath looks like. Just due to this question I asked myself about the difference of the two: Is the property reference (::test) equivalent to a function accessing the property ({ test }) when passed as argument e.g. `() -> String`?
It seems that you are doing something wrong on logical level.
If you are overriding get method of a variable, then you can access it's value through this get method. Thus, why bother with test::get (which is totally different method, by the way, all you are doing is trying to access char from string), when you can just access variable by it's name?

Pass annotation to a function in Kotlin

How can I pass an annotion instance to a function?
I would like to call the java method AbstractCDI.select(Class<T> type, Annotation... qualifiers). But I don't know how to pass an annotation instance to this method.
Calling the constructor like
cdiInstance.select(MyClass::javaClass, MyAnnotation())
is not allowed and the #Annotation-Syntax cdiInstance.select(MyClass::javaClass, #MyAnnotation) is not allowed as parameter, too. How can I archive this?
When working with CDI you usually also have AnnotationLiteral available or at least you can implement something similar rather easy.
If you want to select a class using your annotation the following should do the trick:
cdiInstance.select(MyClass::class.java, object : AnnotationLiteral<MyAnnotation>() {})
Or you may need to implement your specific AnnotationLiteral-class if you require a specific value. In Java that would work as follows:
class MyAnnotationLiteral extends AnnotationLiteral<MyAnnotation> implements MyAnnotation {
private String value;
public MyAnnotationLiteral(String value) {
this.value = value;
}
#Override
public String[] value() {
return new String[] { value };
}
}
In Kotlin however, you can't implement the annotation and extend AnnotationLiteral or maybe I just did not see how (see also related question: Implement (/inherit/~extend) annotation in Kotlin).
If you rather want to continue using reflection to access the annotation then you should probably rather use the Kotlin reflection way instead:
ClassWithAnno::class.annotations
ClassWithAnno::methodWithAnno.annotations
Calling filter, etc. to get the Annotation you desire or if you know there is only one Annotation there, you can also just call the following (findAnnotation is an extension function on KAnnotatedElement):
ClassWithAnno::class.findAnnotation<MyAnnotation>()
ClassWithAnno::methodWithAnno.findAnnotation<MyAnnotation>()
One could annotate a method or field with the annotation an get it per Reflection:
this.javaClass.getMethod("annotatedMethod").getAnnotation(MyAnnotation::class.java)
Or According to Roland's suggestion the kotlin version of the above:
MyClass::annotatedMethod.findAnnotation<MyAnnotation>()!!
As suggested by Roland for CDI it is better to use AnnotationLiteral (see his post).

Object argument to mock EXPECT_CALL

I have a simple mock class:
class MockCanInterface : public lib::CanInterface {
public:
MockCanInterface() : CanInterface({"mock"}) {}
MOCK_METHOD1(Write, bool(const lib::CanFrame& frame));
MOCK_METHOD1(Read, bool(lib::CanFrame* frame));
};
In the test code I want to pass an object to the Write method. Is there a way to do this with .With clause? It works with passing argument directly, but now with .With. The code compiles, but fails during execution - the size of the object is correct, but the data isn't.
This works:
EXPECT_CALL(can_, Write(expected_command_))
.WillOnce(Return(true));
This doesn't:
EXPECT_CALL(can_, Write(_))
.With(Args<0>(expected_command_))
.WillOnce(Return(true));
I admit that there may be something missing in the way the code sets the expected object.
I think the point is: The method Write() required a CanFrame argument passed by reference.
I suggest to use the Actions provided by GMock:
SetArgReferee - reference or value
SetArgPointee - pointer
You can find examples and much more here
However this solution works for me, I hope for you too ;)
EXPECT_CALL(can_, Write(_))
.WillOnce(SetArgReferee<0>(expected_command_));
or with the return value:
EXPECT_CALL(can_, Write(_))
.WillOnce(DoAll(SetArgReferee<0>(expected_command_), Return(true)));

Specifying method's behaviour via EXPECT_CALL vs in body

From what I understand gmock (and I'm new to it) EXPECT_CALL allows for specifying how a method will behave when it's called (in this case I'm mostly interested in what it will return). But I could just as well define the method explicitly with its body. Example:
class Factory
{
int createSomething();
};
class MockFactory : public Factory
{
MOCK_METHOD0(createSomething, int());
};
int main()
{
...
int something(5);
MockFactory mockFactory;
EXPECT_CALL(mockFactory, createSomething()).WillRepeatedly(Return(something));
...
}
vs
class MockFactory : public Factory
{
int createSomething()
{
return 5;
}
};
Now, if createSomething were to behave differently (return different things) in different scenarios then obviously I should use EXPECT_CALL. But if it's going to always return the same thing wouldn't it be better to just explicitly define the method's body? (Note that other methods in the mocked class might still use EXPECT_CALL.)
When you define a method you miss all the flexibility that mocking that method can give you in the tests.
If you need to assert in a test that createSomething gets called, you can only do it if you have mocked it, not if you have a standard method definition. Not in this case, but in case of methods taking parameters, it's even better to have a mock.
If you need to set up a default action that your method should perform, even when you don't set any expectations on it, do so using ON_CALL macro in the SetUp member function of a TestFixture.