I want to test using mockito, that some events are triggered when a javafx ObservableList is modified.
I have tried to to it this way :
#Test
public void handleListChanged() throws Exception {
// [given]
ObservableList<String> list = FXCollections.observableArrayList();
ListChangeListener<String> listener = mock(ListChangeListener.class);
list.addListener(listener);
// [when]
list.add("test");
// [then]
ArgumentCaptor<Change> argument = ArgumentCaptor.forClass(Change.class);
verify(listener).onChanged(argument.capture());
assertTrue(argument.getValue().wasAdded());
}
bu an IllegalStateException raises on the last line :
java.lang.IllegalStateException
at com.sun.javafx.collections.NonIterableChange.checkState(NonIterableChange.java:101)
at com.sun.javafx.collections.NonIterableChange.getPermutation(NonIterableChange.java:81)
at javafx.collections.ListChangeListener$Change.wasPermutated(ListChangeListener.java:156)
at javafx.collections.ListChangeListener$Change.wasAdded(ListChangeListener.java:165)
at FXCollectionsTest.handleListChanged(FXCollectionsTest.java:28
The documentation of the wasAdded() method warns that an IllegalArgumentException could be thrown "if this Change is in initial state" but i don't understand it.
Why my code is not working ?
Is there a solution for testing this code using mockito ?
You must call the next method first on the Change object before you can call any other method like wasAdded.
Unit test
assertTrue(argument.getValue().next());
assertTrue(argument.getValue().wasAdded());
Documentation
public abstract boolean next()
Go to the next change. In initial state is invalid a require a call to next() before calling other methods. The first next() call will make this object represent the first change.
Source
Related
i have two jsf pages (home.jsf and employees.jsf) ,
home page has a button that navigates to employees page,
while navigating i store value in session scope
at (Managed bean)
public void putSessionAL(ActionEvent actionEvent) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("key","value");
}
public String navigate() {
return "employees";
}
i want to change Label at employees viewObject from UIHints tab depending on value stored at session using the following groovy expression
adf.context.sessionScope.key
and changed trustMode to trusted but it fires the following exception
oracle.jbo.script.ExprScriptException: JBO-29114 ADFContext is not setup to process messages for this exception. Use the exception stack trace and error code to investigate the root cause of this exception. Root cause error code is JBO-25188. Error message parameters are {0=Employees.FirstName, 1=, 2=oracle.jbo.script.ExprSecurityException}
at oracle.jbo.script.ExprScriptException.throwException(ExprScriptException.java:316)
at oracle.jbo.script.ExprScriptException.throwExceptionWithExprDef(ExprScriptException.java:387)
at oracle.jbo.ExprEval.processScriptException(ExprEval.java:599)
at oracle.jbo.ExprEval.doEvaluate(ExprEval.java:697)
at oracle.jbo.ExprEval.evaluate(ExprEval.java:508)
at oracle.jbo.ExprEval.evaluate(ExprEval.java:487)
at oracle.jbo.common.NamedObjectImpl.resolvePropertyRaw(NamedObjectImpl.java:680)
at oracle.jbo.server.DefObject.resolvePropertyRaw(DefObject.java:366)
One way to do it at the VO UIHint attribute label level will be programmaticaly by doing as follow :
In your VO go to the java tab and add the RowImpl java class
In the VORowImpl Add the following function
public String getMySessionLabel() {
return (String)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("key");
}
In the Label add the following EL expression :
adf.object.getMySessionLabel()
This technique allow you more control than pure EL, if you want to do more than getting from session for example. In your case pure EL, as you did, should work as well. (Would need to check what is wrong with yours, maybe just missing the
#{adf.context.sessionScope.key}
If you attempt to get your label from a method in viewRowImpl. So this will be executed at least once for each row. I think this solution isn't fit for your case.
anyway ADF as a framework added strong policy and validations in EL in general and especially in version 12.2.x.
The solution for you case as following:
Create new class in model layer which extends oracle.jbo.script.ExprSecurityPolicy class
Override checkProperty method.
#Override
public boolean checkProperty(Object object, String string, Boolean b) {
if (object.getClass().getName().equals("oracle.adf.share.http.ServletADFContext") && string.equals("sessionScope")) {
return true;
}
return super.checkProperty(object, string, b);
}
Open adf-config.xml source and in startup tag set your class ExprSecurityPolicy property.
like:
<startup ExprSecurityPolicy="model.CustomExprSecurityPolicy">
How does the code within the 'shouldFail?' block work? I understand that it is a closure, but the code gets called regardless of whether or not I call is using its signature. Besides, what's the deal with the "ReadOnlyPropertyException" showing up in the parenthesis? If it is a parameter, then it is not setup as listed in the official documentation!!
Questions: What is 'shouldFail'? How should it be invoked? How to handle the exception purportedly thrown by this method/function/closure?
void test02_ReadOnlyFieldInGroovyBean() {
// You've probably noticed how Groovy automatically generates getters/setters for you. But what if you don't
// want to generate a setter because it's a read-only field? Just mark it with 'final'. Groovy will understand.
// Try to modify Ken's ssn. You should get a ReadOnlyPropertyException.
def person = new GroovyPerson('Ken', 'Kousen', '7878')
def failed = false
shouldFail (ReadOnlyPropertyException) {
// ------------ START EDITING HERE ----------------------
System.out.println(" i am in should fail")
person.ssn='8332';
// ------------ STOP EDITING HERE ----------------------
failed = false
System.out.println(" exiting should fail")
}
//def foobar=shouldFail("hjh");
//def foobar=true;
failed=shouldFail('abc');
//System.out.println("Failed: "+failed);
assert failed
// The code wrapping your additions verifies that the ReadOnlyProperty exception has been thrown.
// The curly brackets ({}) represent a closure. We'll get into what that means very soon.
}
shouldFail() (in this variant) takes a class and a closure. It runs the closure and reports a test failure if the closure does NOT exit by throwing an exception of that type. As to catching the exception, you don't - shouldFail() does that for you.
See: http://docs.groovy-lang.org/latest/html/gapi/groovy/test/GroovyAssert.html#shouldFail%28java.lang.Class,%20groovy.lang.Closure%29
(Reading the comments and the code around them, it looks like this unit test should pass because setting the .ssn property of GroovyPerson will fail as it is a read-only property, causing a ReadOnlyPropertyException.)
I just received an exception when I try to reference a static variable in another class, which is also statically initialized. This worked before, and for some reason it fails now. The only changes I made were resetting Visual Studio (2010) to its default setting, which I can't imagine to be the reason for this. Any other code I added didn't touch any of the affected parts either.
This is my code
WinForms class 'MainForm':
partial class MainForm : Form
{
// ...
private RefClass convMan;
private Dictionary<EnumType, string> LogNames = RefClass.LogNames;
// ...
public MainForm() { .... }
}
Referenced class 'RefClass':
class RefClass
{
// ...
public enum EnumType { TypeOne = 0, TypeTwo = 1, TypeThree = 2 };
public static Dictionary<EnumType, string> LogNames = new Dictionary<EnumType, string>()
{
{ EnumType.TypeOne, "Text0" },
{ EnumType.TypeTwo, "Text1" },
{ EnumTypy.TypeThree, "Text2" }
};
}
The error I get now is (translated from German):
An unhandled exception of type "System.TypeInitializationException" occurred.
Additional information: The type initializer for "RefClass" threw an exception.
which has the InnerException
System.ArgumentException
So, as far as I'm concerned, my static dictionary should be initialized once it gets accessed, thus when my Form class references it. I tried debugging to see if the static dictionary is initialized before it gets referenced in the Form class, which is not the case. Also, when I stop at a breakpoint for the reference line, the variable LogNames is null.
I'm really confused as to why this happens, it all worked before.
I found my error, the exceptions I got were quite misleading though. It was a problem with a different dictionary than the one I referenced. It probably didn't get initialized in the first place because something before that failed (If someone can clear this up, please feel free to do so!). Basically what I did wrong was using a two-directional dictionary and adding a value twice. This should normally produce a normal exception, but since it was done statically it got wrapped into a TypeInitializationException. I had a deeper look into the exact stacktrace of the inner exception and found where the exception originated from. Maybe this helps someone in the future...
I had a simular issue getting the same exception. Found that my static constructor for my utility class was generating the exception. Took some time locating since the description of the exception was misleading.
As #Yeehaw mentioned, it appears that the exception gets wrapped, so the common denominator here I would say is that the class/object is static.
I have a class which generates events e.g.
public class EventSource{
public addEventListener(EventListener listener).....
public raiseEvent(){
Event e=....
listener.handle(e);
}
}
I'm using Mockito to mock an EventListener and want to do an equality on the event object (e.g. event.getTime()..event.getMessage() etc). The event object doesnt have an equals method so I cant easily create another object and do an assert.
Whats the normal way of doing this with Mockito?
It looks like you want to use an argument captor.
For example:
ArgumentCaptor<Event> argument = ArgumentCaptor.forClass(Event.class);
verify(mockedListener).handle(argument.capture());
assertEquals("ExpectedMessage", argument.getValue().getMessage());
I have some problems with getting the RefreshRequested event to work in one of my ViewControllers that implements the DialogViewController:
public CustomViewController () : base (null, true) {
RefreshRequested += delegate {
...
ReloadComplete ();
};
}
I am calling the CustomViewController from another ViewController like this:
var dvc = new CustomViewController();
this.ActivateController(dvc);
The error message I get is "Toplevel exception: System.ArgumentException: You should set the handler before the controller is shown"
Any pointers of what I am doing from here? Thanks
It looks like you do not have a RootElement specified, i.e. it's set to null by your own constructor, so you get warned that the internal state is not ready to set the event.
You should create an empty RootElement with your constructor and, later, add stuff to it (using the property). That should allow you to set the event in your own constructor. E.g.
public CustomViewController () : base (new RootElement (String.Empty), true)
Any pointers of what I am doing from here?
In doubt you can always see the entire source code MonoTouch.Dialog in it's github repository.
From my testing, the only place that you can set the event handler is in the constructor of the ViewController, as that's the only place where you can rely on the fact that the TableView property is null. I've tried the suggestion above of setting the RootElement in the constructor, but then always seem to have a TableView object before I can set the event handler. The problem with setting the event handler in the constructor though is that I don't have any way of resetting the event handler after cleaning it up.