unit test - mockito testing to check if another method is invoked - unit-testing

Summary: I am trying to test if a method is invoked once I call one method.
What this class does is, displays information of wrong spelled words and provides u with buttons to 'ignore' or 'ignore all' or 'add to dictionary', etc.
Over here 'ignore' is a JButton declared above.
I am trying to write one test for this method ->
public class SpellCheckerDialog extends JDialog implements ActionListener {
...
..
public void actionPerformed( ActionEvent ev ) {
Object source = ev.getSource();
if( source == ignore ) {
searchNext();
}
}
...
}
Here is what it is invoking, I am testing to see if this method is being invoked or not.
...
//inside same class
public boolean searchNext() {
String wordStr;
while( true ) {
wordStr = tok.nextInvalidWord();
if( wordStr == null ) {
dispose();
String title = SpellChecker.getApplicationName();
if(title == null){
title = this.getTitle();
}
SpellChecker.getMessageHandler().handleInformation( getParent(), title, Utils.getResource( "msgFinish" ) );
return false;
}
if( ignoreWords.contains( wordStr ) ) {
continue;
}
String changeTo = changeWords.get( wordStr );
if( changeTo != null ) {
replaceWord( wordStr, changeTo );
continue;
}
break;
}
word.setText( wordStr );
notFound.setText( wordStr );
List<Suggestion> list = dictionary.searchSuggestions( wordStr );
boolean needCapitalization = tok.isFirstWordInSentence() && Utils.isFirstCapitalized( wordStr );
Vector<String> suggestionsVector = new Vector<String>();
for( int i = 0; i < list.size() && i < options.getSuggestionsLimitDialog(); i++ ) {
Suggestion sugestion = list.get( i );
String newWord = sugestion.getWord();
if( needCapitalization ) {
newWord = Utils.getCapitalized( newWord );
}
if( i == 0 )
word.setText( newWord );
suggestionsVector.add( newWord );
}
suggestionsList.setListData( suggestionsVector );
addToDic.setEnabled( true );
return true;
}
What I have tried until now, tried using Mockito and calling the verify method, but this code snippet seems to not working or have lots of dependencies that I am struggling to get around.
Inside my TestClass, I have this - >
Dialog fr = Mockito.mock(Dialog.class);
SpellCheckerDialog sD = new SpellCheckerDialog(fr);
sD.searchNext();
Mockito.verify(sD, Mockito.times(1)).thenReturn(searchNext());
I don't know if I should be making a stub for my (ActionEvent ev) or ...

Verifications must be done on the mocks created by Mockito, because the framework can't possibly know what happens with objects that it does not manage. This being said, your searchNext() method is part of your class under test so you probably want to spy on it just like in the example below:
public class SpyTest {
class MyClass {
public void callDoSomething(){
doSomething();
}
public void doSomething(){
// whatever
}
}
#Test
public void shouldSpyAndVerifyMethodCall(){
MyClass objectUnderTest = new MyClass();
MyClass spy = Mockito.spy(objectUnderTest);
spy.callDoSomething();
Mockito.verify(spy, Mockito.times(1)).doSomething();
}
}
My advice is to go through the Mockito documentation and examples from the link above, as they're pretty straight-forward and should give you a good starting point.
EDIT as per your comment:
public class SpyTest {
class MyClass {
private JButton myButtton;
public void actionPerformed(ActionEvent event){
if(event.getSource() == myButtton) {
searchNext();
}
}
public void searchNext(){
// whatever
}
}
#Mock // define a mock for the button to "hack" the source check
private JButton mockButton;
#InjectMocks // inject the mock in our object under test
private MyClass objectUnderTest;
#Test
public void shouldSpyAndVerifyMethodCall(){
// spy on our object so we can query various interactions
MyClass spy = spy(objectUnderTest);
// event mock
ActionEvent mockEvent = mock(ActionEvent.class);
// "hack" the source check
when(mockEvent.getSource()).thenReturn(mockButton);
// call main logic
spy.actionPerformed(mockEvent);
// verify interactions
verify(spy).searchNext(); // times(1) not needed because it's the implicit/default setting, see David's comment
}
}

Related

Unit Testing: Verify that a method was called, without testing frameworks like Mockito or MockK

Not using testing frameworks like MockK or Mockito seems to be becoming more and more popular. I decided to try this approach. So far so good, returning fake data is simple. But how do I verify that a function (that does not return data) has been called?
Imagine having a calss like this:
class TestToaster: Toaster {
override fun showSuccessMessage(message: String) {
throw UnsupportedOperationException()
}
override fun showSuccessMessage(message: Int) {
throw UnsupportedOperationException()
}
override fun showErrorMessage(message: String) {
throw UnsupportedOperationException()
}
override fun showErrorMessage(message: Int) {
throw UnsupportedOperationException()
}
}
With MockK I would do
verify { toaster.showSuccessMessage() }
I do not want to reinvent a wheel so decided to ask. Finding anything on Google seems to be very difficult.
Since this is a thing, I assume the point would be to totally remove mocking libraries and everything can be done without them.
The old school way to do it before any appearance of the mocking library is to manually create an implementation that is just for testing . The test implementation will store how an method is called to some internal state such that the testing codes can verify if a method is called with expected parameters by checking the related state.
For example , a very simple Toaster implementation for testing can be :
public class MockToaster implements Toaster {
public String showSuccesMessageStr ;
public Integer showSuccesMessageInt;
public String showErrorMessageStr;
public Integer showErrorMessageInt;
public void showSuccessMessage(String msg){
this.showSuccesMessageStr = msg;
}
public void showSuccessMessage(Integer msg){
this.showSuccesMessageInt = msg;
}
public void showErrorMessage(String msg){
this.showErrorMessageStr = msg;
}
public void showErrorMessage(Integer msg){
this.showErrorMessageInt = msg;
}
}
Then in your test codes , you configure the object that you want to test to use MockToaster. To verify if it does really call showSuccessMessage("foo") , you can then assert if its showSuccesMessageStr equal to foo at the end of the test.
A lot of people seem to be suggesting the very straight forward solution for this, which totally makes sense. I decided to go a bit fancy and achieve this syntax:
verify(toaster = toaster, times = 1).showErrorMessage(any<String>()).
I created simple Matchers:
inline fun <reified T> anyObject(): T {
return T::class.constructors.first().call()
}
inline fun <reified T> anyPrimitive(): T {
return when (T::class) {
Int::class -> Int.MIN_VALUE as T
Long::class -> Long.MIN_VALUE as T
Byte::class -> Byte.MIN_VALUE as T
Short::class -> Short.MIN_VALUE as T
Float::class -> Float.MIN_VALUE as T
Double::class -> Double.MIN_VALUE as T
Char::class -> Char.MIN_VALUE as T
String:: class -> "io.readian.readian.matchers.strings" as T
Boolean::class -> false as T
else -> {
throw IllegalArgumentException("Not a primitive type ${T::class}")
}
}
}
Added a map to store call count for each method to my TestToaster where the key is the name of the function and value is the count:
private var callCount: MutableMap<String, Int> = mutableMapOf()
Whenever a function gets called I increase current call count value for a method. I get current method name through reflection
val key = object {}.javaClass.enclosingMethod?.name + param::class.simpleName
addCall(key)
In oder to achieve the "fancy" syntax, I created inner subcalss for TestToaster and a verify function:
fun verify(toaster: Toaster , times: Int = 1): Toaster {
return TestToaster.InnerToaster(toaster, times)
}
That function sends current toaster instance to the inner subclass to create new instance and returns it. When I call a method of the subclass in my above syntax, the check happens. If the check passes, nothing happens and test is passed, if conditions not met - and exception is thrown.
To make it more general and extendable I created this interface:
interface TestCallVerifiable {
var callCount: MutableMap<String, Int>
val callParams: MutableMap<String, CallParam>
fun addCall(key: String, vararg param: Any) {
val currentCountValue = callCount.getOrDefault(key, 0)
callCount[key] = currentCountValue + 1
callParams[key] = CallParam(param.toMutableList())
}
abstract class InnerTestVerifiable(
private val outer: TestCallVerifiable,
private val times: Int = 1,
) {
protected val params: CallParam = CallParam(mutableListOf())
protected fun check(functionName: String) {
val actualTimes = getActualCallCount(functionName)
if (actualTimes != times) {
throw IllegalStateException(
"$functionName expected to be called $times, but actual was $actualTimes"
)
}
val callParams = outer.callParams.getOrDefault(functionName, CallParam(mutableListOf()))
val result = mutableListOf<Boolean>()
callParams.values.forEachIndexed { index, item ->
val actualParam = params.values[index]
if (item == params.values[index] || (item != actualParam && isAnyParams(actualParam))) {
result.add(true)
}
}
if (params.values.isNotEmpty() && !result.all { it } || result.isEmpty()) {
throw IllegalStateException(
"$functionName expected to be called with ${callParams.values}, but actual was with ${params.values}"
)
}
}
private fun isAnyParams(vararg param: Any): Boolean {
param.forEach {
if (it.isAnyPrimitive()) return true
}
return false
}
private fun getActualCallCount(functionName: String): Int {
return outer.callCount.getOrDefault(functionName, 0)
}
}
data class CallParam(val values: MutableList<Any> = mutableListOf())
}
Here is the complete class:
open class TestToaster : TestCallVerifiable, Toaster {
override var callCount: MutableMap<String, Int> = mutableMapOf()
override val callParams: MutableMap<String, TestCallVerifiable.CallParam> = mutableMapOf()
override fun showSuccessMessage(message: String) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
override fun showSuccessMessage(message: Int) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
override fun showErrorMessage(message: String) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
override fun showErrorMessage(message: Int) {
val key = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
addCall(key, message)
}
private class InnerToaster(
verifiable: TestCallVerifiable,
times: Int,
) : TestCallVerifiable.InnerTestVerifiable(
outer = verifiable,
times = times,
), Toaster {
override fun showSuccessMessage(message: String) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
override fun showSuccessMessage(message: Int) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
override fun showErrorMessage(message: String) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
override fun showErrorMessage(message: Int) {
params.values.add(message)
val functionName = object {}.javaClass.enclosingMethod?.name + message::class.simpleName
check(functionName)
}
}
companion object {
fun verify(toaster: Toaster, times: Int = 1): Toaster {
return InnerToaster(toaster as TestCallVerifiable, times)
}
}
}
I have not tested this extensively and it will evolve with time, but so far it works well for me.
I also wrote an article about this on Medium: https://sermilion.medium.com/unit-testing-verify-that-a-method-was-called-without-testing-frameworks-like-mockito-or-mockk-433ef8e1aff4

PHPUnit: how to mock multiple method calls with multiple arguments and no straight order?

I need to test following function:
[...]
public function createService(ServiceLocatorInterface $serviceManager)
{
$firstService = $serviceManager->get('FirstServiceKey');
$secondService = $serviceManager->get('SecondServiceKey');
return new SnazzyService($firstService, $secondService);
}
[...]
I know, I might test it this way:
class MyTest extends \PHPUnit_Framework_TestCase
{
public function testReturnValue()
{
$firstServiceMock = $this->createMock(FirstServiceInterface::class);
$secondServiceMock = $this->createMock(SecondServiceInterface::class);
$serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);
$serviceManagerMock->expects($this->at(0))
->method('get')
->with('FirstServiceKey')
->will($this->returnValue($firstService));
$serviceManagerMock->expects($this->at(1))
->method('get')
->with('SecondServiceKey')
->will($this->returnValue($secondServiceMock));
$serviceFactory = new ServiceFactory($serviceManagerMock);
$result = $serviceFactory->createService();
}
[...]
or
[...]
public function testReturnValue()
{
$firstServiceMock = $this->createMock(FirstServiceInterface::class);
$secondServiceMock = $this->createMock(SecondServiceInterface::class);
$serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);
$serviceManagerMock->expects($this->any())
->method('get')
->withConsecutive(
['FirstServiceKey'],
['SecondServiceKey'],
)
->willReturnOnConsecutiveCalls(
$this->returnValue($firstService),
$this->returnValue($secondServiceMock)
);
$serviceFactory = new ServiceFactory($serviceManagerMock);
$result = $serviceFactory->createService();
}
[...]
Both workes fine, but if I swap the ->get(xxx) lines in the createService function, both tests will fail.
So, how do I have to change the testcases which doesn't need a specific sequenz for the parameters 'FirstServiceKey', 'SecondServiceKey, ...
You can try with willReturnCallback or willReturnMap strategy, as example of willReturnCallback:
public function testReturnValue()
{
$firstServiceMock = $this->createMock(FirstServiceInterface::class);
$secondServiceMock = $this->createMock(SecondServiceInterface::class);
$serviceManagerMock = $this->createMock(ServiceLocatorInterface::class);
$serviceManagerMock->expects($this->any())
->method('get')
->willReturnCallback(
function ($key) use($firstServiceMock, $secondServiceMock) {
if ($key == 'FirstServiceKey') {
return $firstServiceMock;
}
if ($key == 'SecondServiceKey') {
return $secondServiceMock;
}
throw new \InvalidArgumentException; // or simply return;
}
);
$serviceFactory = new ServiceFactory($serviceManagerMock);
$result = $serviceFactory->createService();
}
Hope this help
It's been a while and so there is a new option to solve this: Change to 'Prophets'
public function testReturnValue()
{
$this->container = $this->prophesize(ServiceLocatorInterface::class);
$firstService = $this->prophesize(FirstServiceInterface::class);
$secondService = $this->prophesize(SecondServiceKey::class);
$this->container->get('FirstServiceKey')->willReturn(firstService);
// And if you like
$this->container->get('FirstServiceKey')->shouldBeCalled();
$this->container->get('SecondServiceKey')->willReturn(secondService);
[...]
$serviceFactory = new ServiceFactory();
/*
* Little error in my example. ServiceLocatorInterface is parameter of
* createService() and not the constructor ;) (ZF2/3)
*/
$result = $serviceFactory->createService(
$this->container->reveal()
);
[...]
}
and now, it doesn't matter, in which sequence you'll make the '$serviceManager->get([...]);' calls \o/

How to write spoon input step plugin?

I am trying to learn how to write an input step plugin, which writes "hello world". I have issues in the Step class.
I have serious problems writing down the processRow function as all the tutorials assume the step to have some input and use getRow ... and inherit the meta structure from the input:
Here's my class (without the processRow body):
public class Test001Plugin extends BaseStep implements StepInterface {
private Test001PluginMeta meta;
private Test001PluginData data;
public Test001Plugin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans) {
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
// Casting to step-specific implementation classes is safe
try{
meta = (Test001PluginMeta) smi;
data = (Test001PluginData) sdi;
if ( super.init(meta, data))
{
return true;
}
else return false;
} catch ( Exception e ) {
setErrors( 1L );
logError( "Error initializing step", e );
return false;
}
}
#SuppressWarnings("deprecation")
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
}
}
May you help me complete the code? or forward me to the appropriate tutorial?
Best Regards

Android: Alarms and IntentServices

After lots of research on implementing IntentServices and Alarms together, I've come up with this. I don't know exactly what happens with this code so I need help in knowing exactly what is going on.
public class MainActivity{
//....
public void onNewItemAdded(String[] _entry){
//...
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
}
//....
}
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent startIntent = new Intent(context, UpdateService.class);
context.startService(startIntent);
}
public static final String ACTION_REFRESH_ALARM = "com.a.b.ACTION_REFRESH_ALARM";
}
public class UpdateService extends IntentService{
//...
#Override
public void onCreate() {
super.onCreate();
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
String ALARM_ACTION = AlarmReceiver.ACTION_REFRESH_ALARM;
Intent intentToFire = new Intent(ALARM_ACTION);
alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
int updateFreq = Integer.parseInt(prefs.getString(
PreferencesActivity.PREF_UPDATE_FREQ, "60"));
boolean autoUpdateChecked = prefs.getBoolean(
PreferencesActivity.PREF_AUTO_UPDATE, false);
if (autoUpdateChecked) {
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long timeToRefresh = SystemClock.elapsedRealtime() + updateFreq
* 60 * 1000;
alarmManager.setInexactRepeating(alarmType, timeToRefresh,
updateFreq * 60 * 1000, alarmIntent);
}
else {
alarmManager.cancel(alarmIntent);
}
refreshKeywords();
}
}
My aim is to get the refreshKeywords() method to be called every minute. Also, what happens if the onNewItemAdded() method is called more than once?
Sorry if this question is stupid, I'm a beginner.
If you wish you to call refreshKeywords()method to be called every minutes why do you use AlarmManager like this,
private void ServiceRunningBackground() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
final int restartAlarmInterval = 6000;
final int resetAlarmTimer = 2*1000;
final Intent restartIntent = new Intent(this, MyService.class);
restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
final AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Handler restartServiceHandler = new Handler()
{
#Override
public void handleMessage(Message msg) {
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
sendEmptyMessageDelayed(0, resetAlarmTimer);
}
};
restartServiceHandler.sendEmptyMessageDelayed(0, 0);
}
}
Just call this method where ever you want and set the time accordingly

C++ Own Observer Pattern

I'm designing an observer pattern which should work this way: observer calls AddEventListener method of EventDispatcher and passes a string which is the name of the event, PointerToItself and a PointerToItsMemberMethod
After that event happens inside of the EventDispatcher; it looks through the list of subscriptions and if there are some, assigned to this event calls the action method of the observer.
I've come to this EventDispatcher.h. CAUTION contains bit of pseudo-code.
The are two questions:
How do I define the type of action in struct Subscription?
Am I moving the right way?
PS: No, I'm not gonna use boost or any other libraries .
#pragma once
#include <vector>
#include <string>
using namespace std;
struct Subscription
{
void* observer;
string event;
/* u_u */ action;
};
class EventDispatcher
{
private:
vector<Subscription> subscriptions;
protected:
void DispatchEvent ( string event );
public:
void AddEventListener ( Observer* observer , string event , /* u_u */ action );
void RemoveEventListener ( Observer* observer , string event , /* u_u */ action );
};
This header implements like this in EventDispatcher.cpp
#include "EventDispatcher.h"
void EventDispatcher::DispatchEvent ( string event )
{
int key = 0;
while ( key < this->subscriptions.size() )
{
Subscription subscription = this->subscriptions[key];
if ( subscription.event == event )
{
subscription.observer->subscription.action;
};
};
};
void EventDispatcher::AddEventListener ( Observer* observer , string event , /* */ action )
{
Subscription subscription = { observer , event , action );
this->subscriptions.push_back ( subscription );
};
void EventDispatcher::RemoveEventListener ( Observer* observer , string event , /* */ action )
{
int key = 0;
while ( key < this->subscriptions.size() )
{
Subscription subscription = this->subscriptions[key];
if ( subscription.observer == observer && subscription.event == event && subscription.action == action )
{
this->subscriptions.erase ( this->subscriptions.begin() + key );
};
};
};
You could either define an Action class or pass a lambda function (C++11). In the latter case, action could be defined as
function<void (EventDispatcher*)> action;
and you would register the observer as follows
Observer * me = this;
observable->AddEventListener (this, "EventName", [me] (EventDispatcher* dispatcher) {
// code here; me is available
});
You should probably use smart weak pointers to store the Observers in the EventDispatcher, such that you do not have to care for un-registering.
Edit: Added following example (just one subscription possible, but should illustrate the idea -- you have to be careful that you do not reference an object that does no longer exist)
struct Observable {
std::weak_ptr<function<void (const Observable&)>> action;
void AddEventListener (std::weak_ptr<function<void (const Observable&)>> theAction) {
action = theAction;
}
void EventRaised () {
if (!action.expired ()) {
auto theAction = action.lock ();
(*theAction) (*this);
}
}
};
struct Observer {
...
void CallOnEvent (const Observable & observable) {
// do something
}
// field to store the action as long as it is needed
std::shared_ptr<function<void (const Observable&)>> action;
void ... {
auto me = this;
action = std::make_shared<function<void (const Observable&)>> (
[me] (const Observable& observable) {
me->CallOnEvent (observable);
}
);
// we could have as well used std::bind
observable.AddEventListener (action);
}
};
Perhaps you should just create a class to be derived by "users":
class Action {
public:
friend class EventDispatcher;
virtual SomeResultType DoThis() = 0;
private:
/* Some common data */
};
Just pass some derived-from-class-Action typed variable to AddEventListener. When the corresponding event is triggered, just fill in the common data and call the DoThis() method.
void EventDispatcher::DispatchEvent ( string event )
{
int key = 0;
while ( key < this->subscriptions.size() )
{
Subscription subscription = this->subscriptions[key];
if ( subscription.event == event )
{
subscription->action();
};
};
};
For AddEventListener:
void EventDispatcher::AddEventListener ( Observer* observer , string event , Action* action )
{
Subscription subscription = { observer , event , action );
this->subscriptions.push_back ( subscription );
};
An example of a Action derived class:
class myAction: public Action {
public:
// Implement the DoThis() method
void SomeResultType DoThis() {
cout << "Hello World!";
return SomeValue;
}
};
// To use the action,
myAction* act = new myAction;
myEventDispatcher.AddEventListener(someObserver, "HelloWorld", act);
This is one of the safest way to implement actions (and callbacks).
In its simplest form u_u could be a function pointer e.g.
typedef void (*u_u)(void*); // or whatever arguments u like
then you just supply a function that is called whenever the event is triggered.
void myaction(void* arg)
{
...
}
Subscription s;
...
s.action = myaction;