instantiating view won't work
Hey guys!
We used to write our UnitTests with FlexUnit and we were just testing our model. Now we want to test the view too. Before i run my tests i create an instance of my view and my model to test the stuff. When i try to access the view i get a null pointer exception. If i add the view to the displaylist it somehow works - even if i remove it from the list right after adding.it looks something like this:开发者_运维百科
var myView: MyView = new myView();
//myView.initialize(); will throw error
Application.application.addChild(view);
Application.application.removeChild(view);
myView.initialize(); // will work
Hope you can give me a hint.
Sims
Flex UIComponents do not walk through the component lifecycle until after they are added to a container. As such, variables may not be initialized and children may not be created if you never add it to a container.
More info on the Flex Component LifeCycle. You'll notice there are 11 steps after the component is added to the container.
I suspect that adding it, then removing it, could cause other issues but it depends what you're trying to test.
To know your exact error, we'd have to see what code is in the initialize method on the view. Most likely it accesses a child that was not created yet.
MXML components will often masks the lifecycle steps, but a component will still go through them.
I hope this helps; but since you didn't ask a question I'm not sure if that was the information you were after.
In addition to what (www.Flextras.com) wrote, which I was just about to post as well, you might consider a different approach to testing your views.
First, consider a separation pattern like Presentation Model, MVP or MVC. They allow you to separate your view from your view behavior and test the behavior separate from the view. An approach like this, when done correctly, will take you a long way because you minimize or eliminate the AS3 code in your view.
If you really want to test your views, I would suggest that you use a functional testing tool for this. Unit test frameworks are good for testing classes in isolation. Once you start talking about views, which have complicated lifecycles, a functional testing framework starts to make sense.
Look at FlexMonkey as an example of a functional UI testing framework for Flex.
I recommend you to use User Interface Facade described here or here. This functionality is designed specially for UI componets testing.
精彩评论