How to verify a method call through a functional interface with Mockito? - java-8

I'm using a Supplier to instantiate a field thread safe while avoiding consecutive calls to the synchronized method.
class MyClass extends AbstractClassWithContext {
Supplier<Foo> fooGetter;
Foo foo;
public MyClass() {
this.fooGetter = this::initFoo;
}
Foo getFoo(){
return fooGetter.get();
}
synchonized Foo initFoo(){
if(Objects.isNull(this.foo)) {
this.foo = getContext().getFoo();
}
this.fooGetter = () -> this.foo;
return this.foo;
}
}
When I'm running my Unit Tests I want to make sure that initFoo() is called exactly once. Sadly verify(classUnderTest, times(1)).initFoo() does not register that initFoo is entered. I debugged this and calling getFoo() does in turn enter initFoo.
Any ideas?

I assume your test code looks something like this:
MyClass spiedOnObject = spy(new MyClass());
spiedOnObject.getFoo();
verify(spiedOnObject , times(1)).initFoo();
The problem is that this.fooGetter = this::initFoo; is called before you start spying on the object. At this point this refers to the real object, not to the spy. And that reference is captured when the method reference is created. Therefore the call cannot be registered.

Related

Difference between "def" and "static def" in Gradle

As the title, what is exactly the difference of these two defs in Groovy?
Maybe it's a documentation problem, I can't find anything...
A method declaration without static marks a method as an instance method. Whereas a declaration with static will make this method static - can be called without creating an instance of that class - see https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
def in groovy defines a value as duck typed. The capabilities of the value are not determined by its type, they are checked at runtime. The question if you can call a method on that value is answered at runtime - see optional typing.
static def means that the method will return a duck typed value and can be called without having instance of the class.
Example:
Suppose you have these two classes:
class StaticMethodClass {
static def test(def aValue) {
if (aValue) {
return 1
}
return "0"
}
}
class InstanceMethodClass {
def test(def aValue) {
if (aValue) {
return 1
}
return "0"
}
}
You are allowed to call StaticMethodClass.test("1"), but you have to create an instance of InstanceMethodClass before you can call test - like new InstanceMethodClass().test(true).

Mocking an extension function with Mockito

How can I test an extension function with Mockito? It doesn't seem to work nicely.
This is my extension function
fun <T> CrudRepository<T, String>.findOneById(id: String): T? {
val o = findById(id)
return if (o.isPresent) o.get() else null
}
And this is what I'm trying to test
#Test
fun getIslandById() {
//given
BDDMockito.given(islandRepository.findOneById("islandId1"))
.willReturn(IslandEntity(tileList, "1", "islandId1")) //findOneById is my extension function
//when
val island = islandService.getIslandById("islandId1")
//then
Assertions.assertThat(island?.id).isEqualTo("islandId1")
}
But the preceeding test throws the following error
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
IslandEntity cannot be returned by findById()
findById() should return Optional
Any ideas?
Instance extension functions can be mocked like this with a little help of mockito-kotlin:
data class Bar(thing: Int)
class Foo {
fun Bar.bla(anotherThing: Int): Int { ... }
}
val bar = Bar(thing = 1)
val foo = mock<Foo>()
with(foo) {
whenever(any<Bar>().bla(any()).doReturn(3)
}
verify(foo).apply {
bar.bla(anotherThing = 2)
}
As I said in a comment above, in the bytecode extension functions are nothing more than static functions which accept receiver as a first argument. Therefore you can't mock an extension function with a Mockito since it is not able to mock static functions.
What you can do, in case that findById(id) is implemented by Repository and not another extension function, is next:
Mock return value of findById(id) instead.
Take a look at the sample code below:
#Test
fun getIslandById() {
//given
BDDMockito.given(islandRepository.findById("islandId1"))
.willReturn(Optional.of(IslandEntity(tileList, "1", "islandId1"))) //mock findById function
//when
val island = islandService.getIslandById("islandId1")
//then
Assertions.assertThat(island?.id).isEqualTo("islandId1")
}
This way you are indirectly mocking your extension by providing it a mocked value that you want it to operate on.
Note: Error that you posted above says that your findById(id) should return an optional. So, wrap your return value of findById(id) function with an optional by calling Optional.of(result).

How can I pass a object using MockMvc as a RequestBody?

So here is the scenario and problem I am facing explained in code
// the call that I am making in my test, please note that myService is a Mocked object
Foo foo = new Foo();
when(myService.postFoo(foo)).thenReturn(true);
mockMvc.perform(post("/myEndpoint")
.contentType(APPLICATION_JSON_UTF8)
.content(toJsonString(foo))
.andExpect(status().isAccepted());
// this is the controller method that get's called
#PostMapping("/myEndpoint")
#ResponseStatus(code = HttpStatus.ACCEPTED)
public String postFoo(#RequestBody Foo foo) {
if (myService.postFoo(foo)) {
return "YAY";
}
return "" + 0 / 0;
}
The problem I am facing is that the foo that is passed in by mockMvc's post is a new instance of Foo, so the if statement for myService.postFoo(foo) fails. I am assuming that the engine used the jsonString of my foo object to create a new one that is field wise identical, however a different object, thus making that 'if' statement fails.
How can I work around this?
Use any(Foo.class) in your mock, than your if should match.
http://static.javadoc.io/org.mockito/mockito-core/2.19.0/org/mockito/ArgumentMatchers.html#any-java.lang.Class-

Is there an equivalent in Dart of the instance_variable_set method in Ruby?

If not, is there anything like this on the horizon?
This is the one feature of JavaScript, Ruby, and Perl that I can't live without. I know you can fake it with a hash member, but I want to be able to create (arbitrary) "first class" members from a parser.
Currently there's nothing that can set a field that doesn't yet exist. The mirror API can be used to set fields that already exist, and may eventually be extended to support defining new fields dynamically.
You can also use the "noSuchMethod" method on a class to intercept setter / getter, and store the received value in a map.
For example (I can't remember the syntax exactly...):
class Foo {
var _dynamicProperties = new Map<String,Object>();
noSuchMethod(String function_name, List args) {
if (args.length == 0 && function_name.startsWith("get:")) {
// Synthetic getter
var property = function_name.replaceFirst("get:", "");
if (_dynamicProperties.containsKey(property)) {
return _dynamicProperties[property];
}
}
else if (args.length == 1 && function_name.startsWith("set:")) {
// Synthetic setter
var property = function_name.replaceFirst("set:", "");
// If the property doesn't exist, it will only be added
_dynamicProperties[property] = args[0];
return _dynamicProperties[property];
}
super.noSuchMethod(function_name, args)
}
}
And then you can use this in your code as follows:
var foo = new Foo();
foo.bar = "Hello, World!";
print(foo.bar);
Of course, this can lead to typos that will not be checked by the type checker, e.g.:
foo.bar = "Hello";
foo.baz = "Hello, World!"; // Typo, meant to update foo.bar.
There are ways you have type-checker validation by using redirecting factory constructors and an implied interface, but then it starts to get complicated.
Side note: This is what JsonObject uses to convert a JSON map to a class type syntax.

boost bind to a data member callback behavior

Can someone please explain this piece of code?
struct Class {
boost::function<void()> member;
};
Class c;
boost::function<boost::function<void()>()> foo = boost::bind(&Class::member, &c);
boost::function<void()> bar = boost::bind(&Class::member, &c);
Why does the definition of bar compile and what is the result of it?
Edit: foo() works as expected, calling c.member(), but bar() doesn't.
The first call is used to "generate" an extractor functor. That functor, when called, will return the member that it was bound to.
The second call just hides the return type of the functor that is passed in (which is the same as in the first example). So essentially, calling bar will do nothing.
You would need to bind if your class was like that:
class Class {
public:
void member();
};
Then what you want to do is that :
Class c;
boost::function<void()> the_function_i_want_to_call = boost::bind(&Class::member, c);
the_function_i_want_to_call.call();

Resources