How to verify a method is called two times with mockito verify() - junit

I want to verify if a method is called at least once through mockito verify. I used verify and it complains like this:
org.mockito.exceptions.verification.TooManyActualInvocations:
Wanted 1 time:
But was 2 times. Undesired invocation:

Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

For Kotlin:
build gradle:
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
code:
interface MyCallback {
fun someMethod(value: String)
}
class MyTestableManager(private val callback: MyCallback){
fun perform(){
callback.someMethod("first")
callback.someMethod("second")
callback.someMethod("third")
}
}
test:
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val uut = MyTestableManager(callback)
uut.perform()
val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()
verify(callback, times(3)).someMethod(captor.capture())
assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")
For Java:
Lombok used to simplify. You can also type out the constructor if you prefer.
build gradle:
testImplementation "org.mockito:mockito-core:3.6.28"
code:
// MyCallback.java
public interface MyCallback {
void someMethod(String value);
}
// MyTestableManager.java
public class MyTestableManager {
private MyCallback callback;
public MyTestableManager(MyCallback callback) {
this.callback = callback;
}
public void perform(){
callback.someMethod("first");
callback.someMethod("second");
callback.someMethod("third");
}
}
test:
import org.mockito.Mockito.times;
import org.mockito.Mockito.verify;
import org.mockito.Mock;
import org.mockito.Captor;
// whatever other imports you need
#Mock
private MyCallback callback;
#Captor
private ArgumentCaptor<String> captor;
private MyTestableManager uut = new MyTestableManager(callback);
// in your test method:
uut.perform()
verify(callback, times(3)).someMethod(captor.capture())
assertTrue(captor.getAllValues().get(0) == "first")
assertTrue(captor.getAllValues().get(1) == "second")
assertTrue(captor.getAllValues().get(2) == "third")

Related

How to mock UUID.randomUuid() and System.currentTimeMillis() without PowerMock?

I am improving my code coverage, and I am using Sonar to compute it.
But Sonar and PowerMock are not very compatible. I was wondering if there is another way to mock UUID.randomUUID() and System.currentTimeMillis() methods without using PowerMock?
I know that PowerMock can introduce difficulties, but I'm not aware of any reason why SonarQube would be incompatible with it.
In any case, recent versions of Mockito can mock static methods (although I haven't used this yet): https://www.baeldung.com/mockito-mock-static-methods .
As rightly noted by #Augusto, one should introduce dependencies instead of relying on static method calls. Then you won't need powermock at all.
Assuming your tools are JUnit5, assertj and mockito. An example goes like this:
// -- production code --
import java.util.UUID;
import java.util.function.Supplier;
public class ProductionCode {
private final Supplier<String> idSupplier;
private final Supplier<Long> clock;
// #VisibleForTesting
ProductionCode(Supplier<String> idSupplier, Supplier<Long> clock) {
this.idSupplier = idSupplier;
this.clock = clock;
}
public ProductionCode() {
this(() -> UUID.randomUUID().toString(), System::currentTimeMillis);
}
public String methodUnderTest() {
return String.format("%s -- %d", idSupplier.get(), clock.get());
}
}
// -- test code without mocking
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class Tests {
#Test
void methodUnderTest_shouldSeparateByDoubleDashRandomIdAndCurrentTime() {
ProductionCode objectUnderTest = new ProductionCode(() -> "id", () -> 1234L);
String s = objectUnderTest.methodUnderTest();
assertThat(s).isEqualTo("id -- 1234");
}
}
// -- test code (mockito) --
import static org.assertj.core.api.Assertions.assertThat;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class Tests {
private final Supplier<String> idSupplier = Mockito.mock(Supplier.class);
private final Supplier<Long> clock = Mockito.mock(Supplier.class);
private final ProductionCode objectUnderTest = new ProductionCode(idSupplier, clock);
#Test
void methodUnderTest_shouldSeparateRandomIdAndCurrentTimeByDoubleDash() {
Mockito.when(idSupplier.get()).thenReturn("id");
Mockito.when(clock.get()).thenReturn(1234L);
String s = objectUnderTest.methodUnderTest();
assertThat(s).isEqualTo("id -- 1234");
}
}

How to create mock instance of Autowired component in Vert.x

I am trying to create mock instance of the class which is autowired inside Verticle but I am getting it as a null. For synchronous code the way which works is looking not useful for Vert.x.
Verticle is:
#Component
public class MyVerticle extends AbstractVerticle{
#Autowired
private ServiceExecutor serviceExecutor;
#Override
public void start() throws Exception {
super.start();
vertx.eventBus().<String>consumer("address.xyz").handler(handleRequest());
}
private Handler<Message<String>> handleRequest() {
return msg -> {
getSomeData(msg.body().toString())
.setHandler(ar -> {
if(ar.succeeded()){
msg.reply(ar.result());
}else{
msg.reply(ar.cause().getMessage());
}
});
};
}
private Future<String> getSomeData(String inputJson) {
Promise<String> promise = Promise.promise();
String data = serviceExecutor.executeSomeService(inputJson); // Getting NPE here. serviceExecutor is coming as null when trying to create mock of it using Mockito.when.
promise.complete(data);
return promise.future();
}
}
Dependent component is:
#Component
public class ServiceExecutor {
public String executeSomeService(String input){
return "Returning Data";
}
}
Test case is:
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
#RunWith(VertxUnitRunner.class)
public class MyVerticleTest {
#Mock
private ServiceExecutor serviceExecutor;
private Vertx vertx;
#Before
public void setup(TestContext ctx){
MockitoAnnotations.initMocks(this);
Async async = ctx.async();
this.vertx = Vertx.vertx();
vertx.deployVerticle(MyVerticle.class.getName(), h -> {
if(h.succeeded()){
async.complete();
}else{
ctx.fail();
}
});
}
#Test
public void test_consumption(TestContext ctx) {
Async async = ctx.async();
when(serviceExecutor.executeSomeService(Mockito.anyString())).thenReturn("Returning Data");
vertx.eventBus().request("address.xyz","message", h ->{
if(h.succeeded()){
ctx.assertEquals("Returning Data",h.result().body().toString());
async.complete();
}else{
ctx.fail(h.cause());
}
});
}
}
Above Test Case works well if I don't use autowired instance to call a method to get the date. But if used it (which I must do to get the data), it is giving NPE at MyVerticle->getSomeData() method when trying to use serviceExecutor object as a mock. This approach works very well for Synchronous code flow but for Vert.x looks like it won't help. So need help here to mock the autowired instance serviceExecutor inside Verticle.
Add a constructor in your MyVerticle
public MyVerticle(ApplicationContext context) {
context.getAutowireCapableBeanFactory().autowireBean(this);
}
and deploy your verticle something like vertx.deployVerticle(new MyVerticle(context),...
I have application context while deploying the verticle and thats what I am passing in the constructor. Check if this works for you.

Unit test WCMUsePOJO class

I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
#Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
#Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
#Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
#Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
#Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
The only thing that you should "have to"* mock is the SlingScriptHelper instance itself, so that it will mimic the dependency injection of the declared service.
Everything else (e.g. the Bindings instance) can be a concrete implementation, for example:
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.junit.Test;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConstantsServiceProviderTest {
private SlingScriptHelper mockSling = mock(SlingScriptHelper.class);
private ConstantsServiceProvider constantsServiceProvider = new ConstantsServiceProvider();
private Bindings bindings = new SimpleBindings();
#Test
public void testFoo() throws Exception {
//Arrange
final String expected = "Hello world";
final ConstantsService testConstantsService = new TestConstantsService(expected);
when(mockSling.getService(ConstantsService.class)).thenReturn(testConstantsService);
bindings.put(SlingBindings.SLING, mockSling);
//Act
constantsServiceProvider.init(bindings);
//Assert
final String actual = constantsServiceProvider.getVar1();
assertThat(actual, is(equalTo(expected)));
}
class TestConstantsService extends ConstantsService {
String var1 = "";
TestConstantsService(String var1) {
this.var1 = var1;
}
#Override
String getVar1() {
return var1;
}
}
}
The entry point here, as you said above, is via the init() method of the WCMUsePojo superclass (as this method is an implementation of the Use.class interface, this test structure also works for testing that via that interface, even if you don't use WCMUsePojo directly.)
*this could be any type of test-double, not necessarily a mock.
You shouldn't create a mock for ConstantsServiceProvider.class if you want to unit-test it. Instead, you should create mocks of its internal objects. So:
Create real instance of ConstantsServiceProvider with new
Mock objects that are returned by getSlingScriptHelper().getService(.) methods. Usually, dependencies are provided (injected) to classes by some container like Spring or simply provided by other classes of your app using setters. In both cases mocks creation is easy.
If your current implementation doesn't allow this - consider refactoring.
You are testing void activate() method which doesn't return anything. So, you should verify calling constantsService.getVar1() method.
I strongly advice you to study Vogella unit-testing tutorial
Here one of possible solution.
The main idea is to have a real object of your class but with overridden getSlingScriptHelper() to return mocked scriptHelper.
I mocked the ConstantsService as well but may be not needed, I don't know your code.
public class ConstantsServiceProviderTest {
#Mock
public SlingScriptHelper scriptHelper;
#Test
public void getVar1ReturnsActivatedValue() throws Exception {
// setup
final String expectedResult = "some value";
// Have a mocked ConstantsService, but if possible have a real instance.
final ConstantsService mockedConstantsService =
Mockito.mock(ConstantsService.class);
Mockito.when(
mockedConstantsService.getVar1())
.thenReturn(expectedResult);
Mockito.when(
scriptHelper.getService(ConstantsService.class))
.thenReturn(mockedConstantsService);
// Have a real instance of your class under testing but with overridden getSlingScriptHelper()
final ConstantsServiceProvider providerWithMockedHelper =
new ConstantsServiceProvider() {
#Override
SlingScriptHelper getSlingScriptHelper() {
return scriptHelper;
}
};
// when
String actualResult = providerWithMockedHelper.getVar1();
// then
assertEquals(expectedResult, actualResult);
}
}

NullPointerException when accessing val field in Scala class constructor

I want to translate something like the following Java code into Scala:
private HashMap<KeyStroke,Action>actionMap=new HashMap<KeyStroke,Action>();
KeyStroke left = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
//....
actionMap.put(left, new AbstractAction("move left") {
#Override
public void actionPerformed(ActionEvent e) {
doSomething();
}
}
My initial attempt was this:
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt._
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.Action
import javax.swing.AbstractAction
import javax.swing.KeyStroke
import collection.mutable.HashMap
object Main{
def main(args:Array[String]){
val gui:GUI = new GUI()
}
}
class GUI extends JFrame{
initKeyboard
pack
this.setVisible(true)
private val actionMap = new HashMap[KeyStroke,Action]
def initKeyboard{
val left = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0)
actionMap.put(left, new AbstractAction("Move Left"){
override def actionPerformed(e:ActionEvent){
println("Do something")
}
})//actionMap.put
}
}
Note that I have not yet written code to do anything with the actionMap.
However I get the following error at runtime:
Java.lang.NullPointerException
at GUI.initKeyboard(Game.scala:24)
at GUI.<init>(Game.scala:18)
at Main$.main(Game.scala:13)
at Main.main(Game.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
(note that line 24 is the line that starts "actionMap.put")
How should this be implemented?
The problem is in the initialization order.
The following is executed on new GUI instance creation, in the order listed:
initKeyboard
pack
this.setVisible(true)
private val actionMap = new HashMap[KeyStroke,Action]
You can see that you call initKeyboard before you initialize actionMap. Therefore accessing it inside initKeyboard throws an exception.
You can verify the initialization order with this simple example:
class GUI extends {
initKeyboard
private val actionMap = println("actionMap")
def initKeyboard: Unit = {
println("initKeyboard")
}
}
new GUI // prints: initKeyboard actionMap

In ActionScript 3.0, can you use addEventListener for one class to react to the function call of another class?

I know how to use addEventListener for one class to react to another class's button being clicked on. What if you want to use it for a more general purpose than that? What if you want to use it to react to one of the member functions of the other class being called? Is there a syntax for that? Thanks!
Edit: Please note that I have already Googled for the answer.
If you want to listen for another class' member function call, you need that function call to dispatch an Event. This is as simple as...
Listener Class
addEventListener("customEvent", listenerFunc);
Dispatcher Class (extends EventDispatcher / implements IEventDispatcher)
dispatchEvent(new Event("customEvent"));
As long as the listener class is above the dispatcher class in the object hierarchy, this will work perfectly. If not, you may want to use some sort of Global EventDispatcher class and register all listeners on that.
You can create your own events and dispatch them from the other class and listen to them in your listening class. Here is some code
In class A (assuming it inherits EventDispatcher)
public function classAMethod():void
{
dispatchEvent(new Event("someCustomTypeForEvent"));
}
In class B (assuming it has a reference to Class A)
public function classBMethod():void
{
classA.addEventListener("someCustomTypeForEvent",customHandler);
}
public function customHandler(e:Event):void
{
trace("handle event");
}
It's like in JAVA for java.awt.Component instances and all Objects that extends java.awt.Component; in AS3 you may add Listeners to all Objects that extends flash.display.Sprite instances which implements methods of IEventDispatcher for you...
So, If you have a class which do not extends flash.display.Sprite, you'll have to extend EventDispatcher in order to add Listeners to your instances and handle Events...
If the class may not extend EventDispatcher, you'll have to implement the IEventDispatcher.
Here is a [class MainClass] that extends [class MovieClip]
This MainClass instance, creates :
An instance of [class ObjectA] which extends [class Object] and implements IEventDispatcher,
An instance of [class ObjectB] which extends [class EventDispatcher]
Here is the code that use the extension method and the implementation method :
I hope this quick done example will help you...
(And sorry for my English, this is not my native language.)
in MainClass.as :
package com
{
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.getQualifiedSuperclassName;
import com.classes.ObjectA;
import com.classes.ObjectB;
import flash.events.Event;
public class MainClass extends flash.display.MovieClip
{
private static const DEBUG:Boolean = true;
private static var instance:MainClass;
private static var instanceOfA:ObjectA;
private static var instanceOfB:ObjectB;
public function MainClass()
{
MainClass.debug("MainClass constructor called");
MainClass.debug(getClassInformations(MainClass));
MainClass.debug(getClassInformations(ObjectA));
MainClass.debug(getClassInformations(ObjectB));
instanceOfA = new ObjectA();
instanceOfB = new ObjectB();
instanceOfA.addEventListener(ObjectA.DO_SOMETHING_EVENT,onInstanceOfA_doSomething,false,0,false);
instanceOfB.addEventListener(ObjectB.DO_SOMETHING_EVENT,onInstanceOfB_doSomething,false,0,false);
instanceOfA.doSomething();
instanceOfB.doSomething();
}
public static function onInstanceOfA_doSomething(e:Event):void
{
trace("An ObjectA has Dispatched An Event of type \"" + e.type + "\"" + " on " + e.target);
}
public static function onInstanceOfB_doSomething(e:Event):void
{
trace("An ObjectB has Dispatched An Event of type \"" + e.type + "\"" + " on " + e.target);
}
public static function getDebugMode():Boolean
{
return DEBUG;
}
public static function debug(string:String)
{
if (getDebugMode())
{
trace(string);
}
}
public static function getClassInformations(someClass:Class):String
{
var clss:Object = null;
var supClss:Object = null;
clss = getDefinitionByName(getQualifiedClassName(someClass));
try
{
supClss = getDefinitionByName(getQualifiedSuperclassName(someClass));
}
catch (e:ArgumentError)
{
// Has no superClass (ex:Object)
}
if (supClss != null)
{
return ("class " + clss + " extends " + supClss);
}
else
{
return ("class " + clss);
}
}
}
}
in ObjectB.as (simplest way):
package com.classes{
import com.MainClass;
import flash.events.EventDispatcher;
import flash.events.Event;
public class ObjectB extends EventDispatcher {
public static var DO_SOMETHING_EVENT:String = "do_something_event";
private var onDoSomethingEvent:Event = new Event(DO_SOMETHING_EVENT,false,false);
public function ObjectB() {
MainClass.debug("constructor ObjectB called");
}
public function doSomething():void{
this.dispatchEvent(onDoSomethingEvent);
}
}
}
in ObjectA.as (there you must implement all the methods of the interface IEventDispatcher):
package com.classes
{
import com.MainClass;
import flash.events.IEventDispatcher;
import flash.events.EventDispatcher;
import flash.events.Event;
public class ObjectA implements IEventDispatcher
{
public static var DO_SOMETHING_EVENT:String = "do_something_event";
private var onDoSomethingEvent:Event = new Event(DO_SOMETHING_EVENT,false,false);
private var dispatcher:EventDispatcher;
public function ObjectA()
{
dispatcher = new EventDispatcher(this);
MainClass.debug("constructor ObjectA called");
}
public function doSomething():void
{
this.dispatchEvent(onDoSomethingEvent);
}
public function addEventListener(
event_type:String,
event_listener:Function,
use_capture:Boolean = false,
priority:int = 0,
weakRef:Boolean = false
):void
{
// implements addEventListener here
dispatcher.addEventListener(event_type, event_listener, use_capture, priority, weakRef);
}
public function dispatchEvent(e:Event):Boolean
{
// implements dispatchEvent here
return dispatcher.dispatchEvent(e);
}
public function removeEventListener(
event_type:String,
event_listener:Function,
use_capture:Boolean = false
):void
{
// implements removeEventListener here
dispatcher.removeEventListener(event_type, event_listener, use_capture);
}
public function hasEventListener(type:String):Boolean
{
// implements hasEventListener here
return dispatcher.hasEventListener(type);
}
public function willTrigger(type:String):Boolean
{
// implements willTrigger here
return dispatcher.willTrigger(type);
}
}
}
Note that if you extend an EventDispatcher, you may also want to override some methods.
In this case, you must use the "override keyword as :
public override function dispatchEvent (e:Event):Boolean {
// a method of EventDispatcher may be overridden if needed !
// do what you need HERE...
return dispatchEvent(e);
}
In AS3 you must specify the override keyword or you'll get an Error 1024:
"Overriding a function that is not marked for override."
When you create a new EventDispatcher through implement or extend, you may also specify additional arguments and methods to this object as:
public function ListenerObject (v:View,m:Main) {
dispatcher = new EventDispatcher(this);
view = v;
master = m;
}
public function getView ():View {
return view;
}
public function getMain ():Main {
return master;
}
then use those methods in the callback method as :
public function callback(e:Event):void{
e.target.getView ();
//...
}