How to verify a method which was called multiple times - mockito

I am working on JUNIT, where i need to verify a method whether it is called or not. so i added below code
verify(mock).method();
When i run i am getting below exception
org.mockito.exceptions.verification.TooManyActualInvocations:
mock.method();
Wanted 1 time:
But was 36 times:
I understand it was invoked 36 times but wanted only one time. help me in fixing this issue

With Mockito you can do that by specifying that your method should be called atleast once.
For example:
verify(mock, atLeastOnce()).method();
For more information: Link

Related

Mockito verify doesn't match multiple stub

It seems that, when I use thenReturn like this:
when(abc.call()).thenReturn(a).thenReturn(b),
I expect:
verify(abc, times(2)).call()
instead, the method seems only get called once, I am a little confused(my test work as expected, the mock seems return the value I expected), but for the invocation times, I don't know if I am getting the wrong result, or it's a expected behavior of the Mockito?
when() is mocking the abc.call() method which has to produce a certain return type. If the method is called once, it will return the value also once, so the stubbing for method invocation is done only once hence the verify only recognizes one call.
You need to customize your function so that the stub(abc.call()) gets called more than once.
You can follow this thread for implementing multiple stubs

NUnit Attribute to simulate condition-based Assert.Inconclusive with custom message text

I have some tests that depend on a certain thing being true (access to the internet, as it happens, but that isn't important and I don't want to discuss the details of the condition).
I can very easily write a static helper method which will test the (parameterless) condition and call Assert.Inconclusive("Explanatory Message") if it's true/false. And then call that at the start of each Test which has this requirement.
But I'd like to do this as an Attribute, if possible.
How, in detail, do I achieve that, in NUnit?
What I've tried so far:
There's an IApplyToTest interface, exposed by NUnit, which I can make my Attribute implement, and will allow me to hook into the TestRunner, but I can't get it to do what I want :(
That interface gives me access to an NUnit.Framework.Internal.Test object.
If I call:
test.RunState = RunState.NotRunnable;
then I get something equivalent to Assert.Fail("").
Similarly RunState.Skipped or RunState.Ignored give me the equivalent of Assert.Ignore("").
But none of these are setting a message on the Test, and there's no test.Message = "foo"; or equivalent (that I can see).
There's a test.MakeInvalid("Foo") which does set a message, but that's equivalent to Assert.Fail("Foo").
I found something that looked promising:
var result = test.MakeTestResult();
result.SetResult(ResultState.Inconclusive, "Custom Message text");
But that doesn't seem to do anything; the Test just Passes :( I looked for a test.SetAsCurrentResult(result) method in case I need to "attach" that result object back to the test? But nothing doing.
It feels like this is supposed to be possible, but I can't quite figure out how to make it all play together.
If anyone can even show me how to get to Skipped + Custom Message displayed, then I'd probably take that!
If you really want your test to be Inconclusive, then that's what Assume.That is there for. Use it just as you would use Assert.That and the specified constraint fails, your test result will be inconclusive.
That would be the simplest answer to your question.
However, reading the things you have tried, I don't think you actually want Inconclusive at least not as it is defined by NUnit.
In NUnit, Inconclusive means that the test doesn't count because it couldn't be run. The result basically disappears and the test run is successful.
You seem to be saying that you want to receive some notice that the condition failed. That makes sense in the situation where (for example) the internet was not available so your test run isn't definitive.
NUnit provides Assert.Ignore and Warn.If (also Warn.Unless) for those situations. Or you can set the corresponding result states in your custom attribute.
Regarding implementation... The RunState of a test applies to it's status before anyone has even tried to execute it. So, for example, the RunState may be Ignored if someone has used the IgnoreAttribute or it may be NotRunnable if it requires arguments and none are provided. There is no Inconclusive run sttate because that would mean the test is written to be inconclusive all the time, which makes no ssense. The IApplyToTest interface allows an attribute to change the status of a test at the point of discovery, before it is even run, so you would not want to use that.
After NUnit has attempted to run a test, it gets a ResultState, which might be Inconclusive. You can affect this in the code of the test but not currently through an attribute. What you want here is something that checks the conditions needed to run the test immediately before running it and skips execution if the conditions are not met. That attribute would need to be one that generates a command in the chain of commands that execute a test. It would probably need to implement ICommandWrapper to do that, which is a bit more complicated than IApplyToTest because the attribute code must generate a command instance that will work properly with NUnit itself and with other commands in the chain.
If I had this situation, I believe I would use a Run parameter to indicate whether the internet should be available. Then, the tests could
Assume.That(InternetIsNotNeeded());
silently ignoring those tests or fail as expected when the internet should be available.

drools linkage error with multiple threads

I have a junit test case which creating two threads to run a application. In this application, there is a method updateStatus which used for fire drools rules. And in this rules file, I have some functions like next :
function Object updateItem() {
.....
}
function boolean isNullOrEmpty(Object obj) {
...
}
function Object getValueFromFact(Object obj) {
....
}
I restart my tomcat, run this unit test, but one thread failed, the error was :
org.apache.cxf.interceptor.Fault: loader (instance of org/drools/rule/JavaDialectRuntimeData$PackageClassLoader): attempted duplicate class definition for name: "com/icil/sofs/booking/rules/GetValueFromFact"
'getValueFromFact' is a function which defined in rules file.
then run it again without restart tomcat, there is no error. then run third time without restart tomcat, there is no error too.
after tried, i found that the 'duplicate class' error only happened at the first time running after restarting tomcat.
i also found that at the first time, 2 threads are execute 'knowldegeSession.execute()' at the "same time", but 2 threads are run 'knowledgeSession.execute()' in sequence at 2nd time and 3rd time.
so why this error 'duplicate class definition' always happened at the first time running after restart tomcat?
and why the error is the function 'getValueFromFact'(this is the 3rd function in rules file) but not the first function 'updateItem'(this is the first function in rules file)?
thanks in advance!
Because there are multiple threads are running 'execute()', and they are loading functions at the 'same time', so this error thrown out.
When calling 'addKnowledgePackages()', drools will load rules, but the functions may not be loaded at this time, they may be loaded when calling 'execute()'.
After debugging, i found that drools will load functions if rules conditions use mvel expression instead of java expression when calling 'addKnowldegePackages()'.
I am using drools 5.5.0.Final, I cannot upgrade drools to 6.0 at present because 6.0 has big difference. But I have to figure out a solution as this problem need to be fixed as soon as possible :
Make your code 'addKnowledgePackages()' can be run when tomcat start, e.g. put it in a static block, as well as change your rules to use mvel expression rather than java expression.

The specified object is not recognized as a fake object. Issue

I am having an issue where a FakeItEasy call in an extremely simple test is failing with the error "The specified object is not recognized as a fake object." The call is simple:
A.CallTo(myService.MyMethod(listOfStringsFilter)).MustHaveHappened();
The fake is similarly simple (A.Fake()), and fakes out an interfance with one method, that takes in a list and returns a list. In debug mode, I see the instance of myService is of type {Fake IMyInterface}. Anyway, this issue is really holding me up, thanks in advance for your help.
Update:
This was my own darn mistake, I needed to make the call say:
A.CallTo(() => myService.MyMethod(listOfStringsFilter)).MustHaveHappened();
This was my own darn mistake, I needed to make the call say:
A.CallTo(() => myService.MyMethod(listOfStringsFilter)).MustHaveHappened();

NSFetchResults update delegate works first time, crashes second time

I've looked around SO for similar answers, but my issue seems a litte different.
I have a UITableView that is tied to a NSFetchResultsController. The goal is to pull up some data, add a couple rows into the Context, and the table is automatically updated. Simple, right?
init -> empty table -> performFetch -> create some objects in the Context -> delegate sees this and updates my table.
I'm using the boilerplate NSFetchResultsController for noticing when the current context has been modified.
When I run this with a clean Simulator/iOS platform, the NSFetchController successfully recognizes that data in the Context has been updated. But if I run the app a second time, I get the following error:
CoreData: error: Serious application error. Exception was caught during Core Data change
processing. This is usually a bug within an observer of
NSManagedObjectContextObjectsDidChangeNotification. *** -[__NSArrayI objectAtIndex:]:
index 40 beyond bounds for empty array with userInfo (null)
The crash occurs on calling [self.tableView beginUpdates];
In my debugging I can see that '[fetchedResultsController fetchedObjects]' is completely empty and I think thats the problem - shouldn't this be updating with my test data since I modified the context? I'm using the Apple Recipe and CoreDataBooks examples as reference.
I think this is because you Data Modle in class just not fit the entity in you .xcdatamodeld file.

Resources