I need it in FlexUnit to test private methods. Is there any possibility to do this via reflection by using describeType or maybe flexUnit has some build in facility? I dislike artificial limitation that i cannot test private functions, it greatly reduces flexibility. Yes it is good design for me to test private functions, so please do not advise me to refactor my code. I do not want to break the encapsulation for the sake of unit testing.
I'm 99% certain this isn't possible and I'm intrigued to know why you would want to do this.
You should be unit testing the output of a given class, based on given inputs, regardless of what happens inside the class. You really want to allow someone to be able to change the implementation details so long as it doesn't change the expected outputs (defined by the unit test).
If you test private methods, any changes to the class are going to be tightly coupled to the unit tests. if someone wants to reshuffle the code to improve readability, or make some updates to improve performance, they are going to have to update the unit tests even though the class is still functioning as it was originally designed.
I'm sure there are edge cases where testing private methods might be beneficial but I'd expect in the majority of cases it's just not needed. You don't have to break the encapsulation, just test that your method calls give correct outputs... no matter what the code does internally.
Just create a public method called "unitTest" and call all your unit tests within that method. Throw an error when one of them fails and call it from your test framework:
try {
myobject.unitTest();
} catch (Exception e) {
//etc.
}
You cannot use describeType for that.
From the Livedocs - flash.utils package:
[...]
Note: describeType() only shows public properties and methods, and will not show
properties and methods that are private, package internal or in custom namespaces.
[...]
When the urge to test a private method is irresistible I just create a testable namespace for the method.
Declare a namespace in a file like this:
package be.xeno.namespaces
{
public namespace testable = "http://www.xeno.be/2015/testable";
}
Then you can use the testable as a custom access modifier for the method you want to test like this:
public class Thing1
{
use namespace testable;
public function Thing1()
{
}
testable function testMe() : void
{
}
}
You can then access that modifier by using the namespace in your tests:
public class Thing2
{
use namespace testable;
public function Thing2()
{
var otherThing : Thing1 = new Thing1();
otherThing.testMe();
}
}
Really though I think this is a hint that you should be splitting your functionality into a separate class.
Related
I'm trying to get an understanding of which concrete types are providing the implementations of interfaces in an IOC (dependency injection) container. My implementation works fine when there are no delegates involved. However, I'm having trouble when a delegate method is passed as the type factory, as I can't get Mono.Cecil to give me the concrete type or a method reference to the factory back. I'm specifically in this case trying to build a component that can work with the IServiceCollection container for .Net ASP.Net REST APIs. I've created a 'minimised' set of code below to make it easy to explain the problem.
Consider the following C# code:
interface IServiceProvider {}
interface IServiceCollection {}
class ServicesCollection : IServiceCollection {}
interface IMongoDBContext {}
class MongoDBContext : IMongoDBContext
{
public MongoDBContext(string configName) {}
}
static class Extensions
{
public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
{
return null;
}
}
class Foo
{
void Bar()
{
IServiceCollection services = new ServicesCollection();
services.AddSingleton<IMongoDBContext>(s => new MongoDBContext("mongodbConfig"));
}
}
When successfully locating the 'services.AddSingleton' as a MethodReference, I'm unable to see any reference to the MongoDBContext class, or its constructor. When printing all the instructions .ToString() I also cannot seem to see anything in the IL - I do see the numbered parameter as !!0, but that doesn't help if I can't resolve it to a type or to the factory method.
Does anyone have any ideas on how to solve this?
Most likely your code is looking in the wrong place.
C# compiler will try to cache the conversion of lambda expression -> delegate.
if you look in sharplab.io you'll see that the compiler is emitting an inner class '<>c' inside your Foo class and in that class it emits the method '<Bar>b__0_0' that will be passed as the delegate (see opcode ldftn).
I don't think there's an easy, non fragile way to find that method.
That said, one option would be to:
Find the AddSingleton() method call
From there start going back to the previous instructions trying to identify which one is pushing the value consumed in 1 (the safest way to do that would be to consider how each instruction you are visiting changes the stack). In the code I've linked, it would be IL_0021 (a dup) of Bar() method.
From there, do something similar to 2, but now looking for the instruction that pushes the method reference (a ldftn) used by the ctor of Func<T, R>; in the code linked, it would be IL_0016.
Now you can inspect the body (in the code linked, Foo/'<>c'::'<Bar>b__0_0')
Note that this implementation has some holes though; for instance, if you call AddSingleton() with a variable/parameter/field as I've done (services.AddSingleton(_func);) you'll need to chase the initialization of that to find the referenced method.
Interestingly, at some point Cecil project did support flow analysis (https://github.com/mono/cecil-old/tree/master/flowanalysis).
If you have access to the source code, I think it would be easier to use Roslyn to analyze it (instead of analyzing the assembly).
I'm a newbie on symfony, And I don't understand the advantage of use service instead of write the cose in Controller
For Example, I Have a service that Create Log, with a code like this:
$path = $root.'/../web';
$fs->touch($path.'/log.txt');
$this->file = $path.'/log.txt';
file_put_contents($this->file, $msg, FILE_APPEND | LOCK_EX);
I can put this login in service with DIC ($fs is FileSystem service), or I can Put this Login on my Controller.
Of course If i Need to log often I have to write the same code. The main advantage is decoupling?
Thanks a lot
Suppose you have a Bar class which uses BasicLogger.
You have a few ways to get access to this logger, lets start with the most simple option:
<?php
class Bar
{
public function bar()
{
$logger = new BasicLogger();
$logger->log("foo");
}
}
This is bad practice because we are mixing construction logic with application logic. It still works, but it has the following drawbacks:
It mixes responsibilities.
Bar becomes hard to test and cannot be tested without side effects.
We cannot dynamically change loggers (code is less reusable).
To solve these drawbacks, we can instead require our Logger class through the constructor.
Our code now looks like this:
class Bar
{
private $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function bar()
{
$this->logger->log("foo");
}
}
Great, our class is no longer responsible for creating the logger, we can test our code without side effects (and make assertions against how the logger was used) and we can now use any logger we like.
So now we use our new class all over the application.
$logger = new Logger();
$bar = new Bar($logger);
Look familiar?
Again we are mixing construction logic with application logic, which we already know is bad.
Not only that, but something even worse is happening here, Code duplication.
Thats right. and every time we want to use our Bar class, the duplication gets worse.
The solution? Use the Service container
Registering your logger as a service would mean that all of your code that needs logging functionality is no longer dependent on your specific logger, responsibilities will not be mixed, code duplication will be reduced and your design will become more flexible.
The main goal and advantage of services is that keep reusable code and use a DRY approach.
Of course, there is a lot of other advantages that you discover progressively as you use them.
Services are accessible from whatever context of your application that can accesses the service container, not only controllers.
If without the service the few lines of code you give would be duplicated in several methods/contexts, you should keep your service.
Otherwise, delete it and do your logic in the specific method.
I think the better approach to use them is at your own feeling.
Don't try to create services in prevention, use them to solve a real need.
When you have a block of code that is duplicated, you should naturally avoid it by creating a service (or other AbstractController that your controllers can extend and inherit the code block) .
The goal is: Always keep a light code and avoid duplicates as possible.
For that, you can use the powerful services of Symfony, or just use the inheritance of classes and other POO principles.
Using https://insight.sensiolabs.com to scan / check my code, I get the following warning:
The Doctrine Entity Manager should not be passed as an argument.
Why is it such a bad practice to inject the Entity Manager in a service? What is a solution?
With respect to the comment that repositories cannot persist entities.
class MyRepository extends EntityRepository
{
public function persist($entity) { return $this->_em->persist($entity); }
public function flush () { return $this->_em->flush (); }
I like to make my repositories follow more or less a "standard" repository interface. So I do:
interface NyRepositoryInterface
[
function save($entity);
function commit();
}
class MyRepository extends EntityRepository implements MyRepositoryInterface
{
public function save ($entity) { return $this->_em->persist($entity); }
public function commit() { return $this->_em->flush (); }
This allows me to define and inject non-doctrine repositories.
You might object to having to add these helper functions to every repository. But I find that a bit of copy/paste is worth it. Traits might help here as well.
The idea is move away from the whole concept of an entity manager.
I am working on a quite a large project currently and have recently started following the approach with repositories that can mutate data. I don't really understand the motivation behind having to inject EntityManager as a dependency which is as bad as injecting ServiceManager to any class. It is just a bad design that people try to justify. Such operations like persist, remove and flush can be abstracted into sth like AbstractMutableRepository that every other repository can inherit from. So far it has been doing quite well and makes code more readable and easier to unit test!
Show me at least one example of a service that has EM injected and unit test for it looked correctly? To be able to unit test sth that has EM injected is more about testing implementation than anything else. What happens is then you end up having so many mocks set up for it, you cannot really call it a decent unit test! It is a code coverage hitter, nothing more!
I'm setting up a functional test suite for an application that loads an external configuration file. Right now, I'm using flexunit's addAsync function to load it and then again to test if the contents point to services that exist and can be accessed.
The trouble with this is that having this kind of two (or more) stage method means that I'm running all of my tests in the context of one test with dozens of asserts, which seems like a kind of degenerate way to use the framework, and makes bugs harder to find. Is there a way to have something like an asynchronous setup? Is there another testing framework that handles this better?
It is pretty easy, but took me 2 days to figure it out.
The solution:
First you need to create a static var somewhere.
public static var stage:Stage
There is a FlexUnitApplication.as created by the flexunit framework, and at the onCreationComplete() function, you can set the stage to the static reference created previously:
private function onCreationComplete():void
{
var testRunner:FlexUnitTestRunnerUIAS=new FlexUnitTestRunnerUIAS();
testRunner.portNumber=8765;
this.addChild(testRunner);
testStageRef.stage=stage //***this is what I've added
testRunner.runWithFlexUnit4Runner(currentRunTestSuite(), "testsuitename");
}
and when you would access the stage in the program, you should replace it to:
if(stage==null) stage=testStageRef.stage
Assuming you're using FlexUnit 4, addAsync can be called from a [BeforeClass] method:
public class TestFixture
{
[BeforeClass]
public static function fixtureSetup() : void
{
// This static method will be called once for all the tests
// You can also use addAsync in here if your setup is asynchronous
// Any shared state should be stored in static members
}
[Test]
public function particular_value_is_configured() : void
{
// Shared state can be accessed from any test
Assert.assertEquals(staticMember.particularValue, "value");
}
}
Having said that, testing code that accesses a file is really an integration test. I'm also hardly in a position to argue against using ASMock :)
Sounds like you need to remove the dependency of loading that external file. Pretty much all Aysnchronous tests can be removed through the use of a mocking frameworks. ASMock is an awesome choice for Flex. It will allow you to fake the URLoader object and return faked configurations to run your tests against. Mocking will help with you write much better unit tests as you can mock all dependencies synchronous or asynchronous.
This question is meant to apply to interfaces in general, but I'll use AS3/Flex for my language. It should be [mostly] obvious how to apply it in different languages.
If I create a base class, and it extends an interface, there is an explicit contract defined: for every method in the interface, the base class must implement said method.
This is easy enough. But I don't understand why you have the capacity to cast an interfaced instance back to its original base class. Of course, I've had to do this a few times (the example below is very close to the situation I'm struggling with), but that doesn't mean I understand it :^)
Here's a sample interface:
public interface IFooable extends IUIComponent {
function runFoo():void;
}
Let's say I create a base class, which extends VBox and implements the interface:
public class Foo extends VBox implements IFooable {
public Foo() {
super();
//stuff here to create Foo..blah blah
}
public function runFoo():void {
// do something to run foo
}
}
Now, the reason I used the interface, is because I want to guarantee "runFoo" is always implemented. It is a common piece of functionality all of my classes should have, regardless of how they implement it. Thus, my parent class (an Application) will instantiate Foo via its interface:
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100; //works because of IUIComponent
}
But, if I want to add Foo to the Application container, I now have to cast it back to the base class (or to a different base class):
public function init():void {
var foo:IFooable = new Foo();
foo.percentHeight = 100;
addChild(foo as DisplayObject); //_have_ to cast, because addChild takes a 'DisplayObject' class type
//could also do this:
//addChild(foo as VBox);
}
Wasn't the original intention to hide the implementation of Foo? There is still an assumption that Foo is a DisplayObject. Unfortunately, being able to add the custom object to a container seems impossible without casting.
Am I missing something entirely? Is this really just a phenomenon in Flex/AS3? If you have a container in the base API of a language, and it only allows you to add children of a certain class type, how do you then abstract out implementation?
For the record, this question appears to ask if this sort of operation is possible, but it doesn't really address why it might be bad design (and how to fix it).
2nd Thought:
Abstract Classes:
As Matthew pointed out, abstract classes helps solve some of this: I could create a base abstract class which inherits from the DisplayObject (or, in my case, the VBox, since it is a child of DisplayObject), and have the base class implement the interface. Thus, any class which extends the abstract class would then be required to implement the methods therein.
Great idea -- but AS3 doesn't have abstract classes (to my knowledge, anyway).
So, I could create a base class which implements interface and extends the VBox, and inherit from it, and I could insert code in those methods which need to be extended; such code would throw an error if the base class is the executor. Unfortunately, this is run-time checking as opposed to compile-time enforcement.
It's still a solution, though.
Context:
Some context might help:
I have an application which can have any number of sub-containers. Each of these sub-containers will have their own respective configuration options, parameters, etc. The application itself, however, has a global ApplicationControlBar which will contain the entry-point Menu for accessing these configuration options. Therefore, whenever I add a sub-component to the main Application (via "addChild"), it will also "register" its own configuration options with the ApplicationControlBar menu. This keeps the knowledge of configurability with the containers themselves, yet allows for a more unified means of accessing them.
Thus, when I create each container, I want to instantiate them via their interface so I can guarantee they can register with the ApplicationControlBar. But when I add them to the application, they need to be the base class.
#James Ward, That's definitely something I wish was in the language, probably a interface IDisplayObject. That would solve a lot of issues in OOP display programing in AS3.
In regards the the original question, something I've used in the past, and have seen mentioned on www.as3dp.com is to include a getDisplay():DisplayObject method in the interface, which would typically return "this" by its implementor. It's less than ideal, but works.
#Matthew Flaschen, While we don't have Abstarct Classes native to AS3, common practice is to name the class with the word Abstract ie: AbstarctMyObject, and then just treat it like the abstarct objects in Java and other languages. Our want for true abstarct classes is something the Flash player team is well aware of, and we'll likly see it in the next version of the ActionScript language.
Okay, I'm anaswering generally, because you said, "Is this really just a phenomenon in Flex/AS3?".
In your init method, obviously you're always calling addChild with foo. That means foo must always be an instance of DisplayObject. You also want it to be an instance of IFooable (though it's not clear here why). Since DisplayObject is a class, you would consider using a subclass of DisplayObject (e.g. FooableDisplayObject), that implemented IFooable. In Java, this would the below. I'm not familiar with AS, but I think this shows there's not any general flaw in interfaces here.
interface IFooable
{
public void runFoo();
}
class DisplayObject
{
}
abstract class FooableDisplayObject extends DisplayObject implements IFooable
{
}
class Foo extends FooableDisplayObject
{
public void runFoo()
{
}
}
public void init()
{
FooableDisplayObject foo = new Foo();
foo.percentHeight = 100;
addChild(foo);
}
I think this is a place where Flex's/Flash's API is not correct. I think that addChild should take an interface not a class. However since that is not the case you have to cast it. Another option would be to monkey patch UIComponent so that it takes an interface or maybe add another method like addIChild(IUIComponent). But that's messy. So I recommend you file a bug.
Situation here is that it should be just the other way around for optimal practice... you shouldn't look to cast your interface to a displayobject but to have your instance already as a displayobject and then cast that to your interface to apply specific methods.
Let's say I have a baseclass Page and other subclasses Homepage, Contactpage and so on. Now you don't apply stuff to the baseclass as it's kind of abstract but you desing interfaces for your subclasses.
Let's say sub-pages implement for example an interface to deal with init, addedtostage, loader and whatever, and another one that deals with logic, and have eventually the base req to be manageble as displayobjects.
Getting to design the implementation.. one should just use an interface for specialized stuff and extend the subclass from where it mainly belongs to.. now a page has a 'base' meaning to be displayed (design wise.. the 'base'-class is a displayobject) but may require some specialization for which one builds an interface to cover that.
public class Page extends Sprite{...}
public interface IPageLoader{ function loadPage():void{}; function initPage():void{}; }
public class Homepage extends Page implements IPageLoader
{ function loadPage():void{/*do stuff*/}; function initPage():void{/*do stuff*/}; }
var currentpage:Page;
var currentpageLoader:IPageLoader;
currentpage = new Homepage;
currentpageLoader = currentpage as IPageLoader;
currentpageLoader.loadPage();
currentpageLoader.initPage();
addChild(currentpage);
Tween(currentpage, x, CENTER);