How can I find out what argument was given to a mocked method? - actionscript-3

If I write something like this:
verify().that( mockPromise.handleFault( any() ))
it works fine to tell me that 'handleFault' was invoked.
But later I want to invoke the fault handler function that was passed in. The handler will be a private function so there isn't another way to access it.

In Java Mockito, the feature you're looking for is called ArgumentCaptor. In short, it's a special kind of Matcher (like any()) that matches any type of object and keeps the object it "matches" in a variable.
Unfortunately, it looks like it's not available in Flex yet.
The good news is that if you feel like it, you can probably write an implementation of the Matcher interface that does exactly that--save its most recent value and return true--in fifteen minutes or so. :)
Good luck!

Based on Jeff's answer, I did this:
import org.mockito.api.Matcher;
class ArgumentCaptor implements Matcher
{
private var _value:*;
public function ArgumentCaptor()
{
}
public function get value():*
{
return _value;
}
public function describe():String
{
return "";
}
public function matches(value:*):Boolean
{
_value = value;
return true;
}
}
which can be used like:
var argCaptor:ArgumentCaptor = new ArgumentCaptor();
verify().that( mockPromise.handleFault( argThat(argCaptor) ));
argCaptor.value; // the argument

Related

How can I pass a function as input for a class in Processing

I am making a framework for making fractals in processing, however, I need to use functions as parameters for a constructor of a class.
Something like:
class Fractal {
String name;
void initialize;
Fractal(String Name, void setup) {
...
}
}
I'm going to guess you're coming from a JavaScript background?
Traditionally, Java didn't really have a way to do this. Instead you'd pass an anonymous instance of an interface, like this:
interface Runner{
public void run();
}
class Fractal {
String name;
Runner initialize;
Fractal(String name, Runner setup) {
...
}
}
Runner r = new Runner(){
public void run(){
// whatever
}
}
Fractal fractal = new Fractal("name here", r);
Note that Java provides a Runnable interface that you can use instead of creating your own, but I wanted to spell it out here to make it more obvious.
As of Java 8, you can pass a reference to a function as a parameter. This is called a lambda function. Googling "Java lambda function" will return a ton of results.
From this answer:
public void pass() {
run(()-> System.out.println("Hello world"));
}
public void run(Runnable function) {
function.run();
}
Depending on how you're using Processing, you might be stuck with the first approach though, since I don't think the Processing editor supports Java 8 yet.

Using JSON.stringify in conjunction with TypeScript getter/setter

I am using getter/setter accessors in TypeScript. As it is not possible to have the same name for a variable and method, I started to prefix the variable with a lower dash, as is done in many examples:
private _major: number;
get major(): number {
return this._major;
}
set major(major: number) {
this._major = major;
}
Now when I use the JSON.stringify() method to convert the object into a JSON string, it will use the variable name as the key: _major.
As I don't want the JSON file to have all keys prefixed with a lower dash, is there any possibility to make TypeScript use the name of the getter method, if available? Or are there any other ways to use the getter/setter methods but still produce a clean JSON output?
I know that there are ways to manually modify the JSON keys before they are written to the string output. I am curious if there is simpler solution though.
Here is a JSFiddle which demonstrates the current behaviour.
No, you can't have JSON.stringify using the getter/setter name instead of the property name.
But you can do something like this:
class Version {
private _major: number;
get major(): number {
return this._major;
}
set major(major: number) {
this._major = major;
}
toJsonString(): string {
let json = JSON.stringify(this);
Object.keys(this).filter(key => key[0] === "_").forEach(key => {
json = json.replace(key, key.substring(1));
});
return json;
}
}
let version = new Version();
version.major = 2;
console.log(version.toJsonString()); // {"major":2}
based on #Jan-Aagaard solution I have tested this one
public toJSON(): string {
let obj = Object.assign(this);
let keys = Object.keys(this.constructor.prototype);
obj.toJSON = undefined;
return JSON.stringify(obj, keys);
}
in order to use the toJSON method
I think iterating through the properties and string manipulating is dangerous. I would do using the prototype of the object itself, something like this:
public static toJSONString() : string {
return JSON.stringify(this, Object.keys(this.constructor.prototype)); // this is version class
}
I've written a small library ts-typed, which generate getter/setter for runtime typing purpose. I've faced the same problem when using JSON.stringify(). So i've solved it by adding a kind of serializer, and proposing to implement a kind of toString (in Java) buy calling it toJSON.
Here is an example:
import { TypedSerializer } from 'ts-typed';
export class RuntimeTypedClass {
private _major: number;
get major(): number {
return this._major;
}
set major(major: number) {
this._major = major;
}
/**
* toString equivalent, allows you to remove the _ prefix from props.
*
*/
toJSON(): RuntimeTypedClass {
return TypedSerializer.serialize(this);
}
}
A new answer to an old question. For situations where there is no private field for a getter/setter, or where the private field name is different to the getter/setter, we can use the Object.getOwnPropertyDescriptors to find the get methods from the prototype.
https://stackoverflow.com/a/60400835/2325676
We add the toJSON function here so that it works with JSON.stringify as mentioned by other posters. This means we can't call JSON.stringify() within toJSON as it will cause an infinite loop so we clone using Object.assign(...)
I also removed the _private fields as a tidyup measure. You may want to remove other fields you don't want to incude in the JSON.
public toJSON(): any {
//Shallow clone
let clone: any = Object.assign({}, this);
//Find the getter method descriptors
//Get methods are on the prototype, not the instance
const descriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(this))
//Check to see if each descriptior is a get method
Object.keys(descriptors).forEach(key => {
if (descriptors[key] && descriptors[key].get) {
//Copy the result of each getter method onto the clone as a field
delete clone[key];
clone[key] = this[key]; //Call the getter
}
});
//Remove any left over private fields starting with '_'
Object.keys(clone).forEach(key => {
if (key.indexOf('_') == 0) {
delete clone[key];
}
});
//toJSON requires that we return an object
return clone;
}
Isn't dynamic but it work
export class MyClass{
text: string
get html() {
return this.text.toString().split("\n").map(e => `<p>${e}</p>`).join('');
}
toJson(): string {
return JSON.stringify({ ...this, html: this.html })
}
}
In calling
console.log(myClassObject.toJson())

In Dart, can you call another constructor from a constructor

That is, I'm trying to invoke one constructor from another, and then construct further. I can't figure out from documentation if it can be done.
Here's a contrived example, in case it helps:
class Chipmunk {
Chipmunk.named(this.name);
Chipmunk.famous() {
this.named('Chip'); // <-- What, if anything, goes here?
this.fame = 1000;
}
}
var chip = new Chimpmunk.famous();
There are two possible ways to do this:
class Chipmunk {
String name;
int fame;
Chipmunk.named(this.name, [this.fame]);
Chipmunk.famous1() : this.named('Chip', 1000);
factory Chipmunk.famous2() {
var result = new Chipmunk.named('Chip');
result.fame = 1000;
return result;
}
}
Chipmunk.famous1() is a redirective constructor. You can't assign properties in this one, so the constructor you are calling has to allow all the properties you want to set. That's why I added fame as an optional parameter. In this case you could make name and fame final.
Chipmunk.famous2() is a factory constructor and can just create the instance you want. In this case, fame couldn't be final (obviously it could be if you used the fame parameter in the named constructor).
The first variant would probably be the preferable one for your use case.
This is the documentation in the language spec:
A generative constructor consists of a constructor name, a constructor parameter list, and either a redirect clause or an initializer list and an optional body.
https://dart.dev/docs/spec/latest/dart-language-specification.html#h.flm5xvbwhs6u
The init pattern could be used here : the constructor just calls an init function defined in the class.
It can have an advantage over the redirective constructor in some cases, i can think of two right now :
- if you are saving/restoring the state of your object (in this case, you just write once the restore part).
- if you are pooling (recycling) your objects and need to 'refresh' them when you revive them.
class Chipmunk {
Chipmunk.named(string newName) { nameInit(newName) };
Chipmunk.famous() {
famousInit();
}
nameInit(string newName) {
name = newName ;
}
famousInit() {
nameInit('Chip');
fame = 1000;
}
string name;
num fame;
}
var chip = new Chimpmunk.famous();
Another way is to use a static method that returns an instance of the same class.
It's technically not a constructor and it's not recommended by the Dart Linter, but it can help in situations where you need to choose which constructor to call depending on the value of an argument.
class Chipmunk {
Chipmunk.named(this.name, [this.fame]);
// ignore: prefer_constructors_over_static_methods
static Chipmunk withFame(int fame) {
if (fame > 100) {
return Chipmunk.named('Super Famous Chip', fame);
}
return Chipmunk.named('Chip', fame);
}
String name;
int? fame;
}
var superFamousChip = Chipmunk.withFame(110);

Simple LINQ to SQL extension method

How would I write a simple LINQ to SQL extension method called "IsActive" which would contain a few basic criteria checks of a few different fields, so that I could reuse this "IsActive" logic all over the place without duplicating the logic.
For example, I would like to be able to do something like this:
return db.Listings.Where(x => x.IsActive())
And IsActive would be something like:
public bool IsActive(Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
Otherwise, I am going to have to duplicate the same old where criteria in a million different queries right throughout my system.
Note: method must render in SQL..
Good question, there is a clear need to be able to define a re-useable filtering expression to avoid redundantly specifying logic in disparate queries.
This method will generate a filter you can pass to the Where method.
public Expression<Func<Listing, bool>> GetActiveFilter()
{
return someListing => someListing.Approved && !someListing.Deleted;
}
Then later, call it by:
Expression<Func<Filter, bool>> filter = GetActiveFilter()
return db.Listings.Where(filter);
Since an Expression<Func<T, bool>> is used, there will be no problem translating to sql.
Here's an extra way to do this:
public static IQueryable<Filter> FilterToActive(this IQueryable<Filter> source)
{
var filter = GetActiveFilter()
return source.Where(filter);
}
Then later,
return db.Listings.FilterToActive();
You can use a partial class to achieve this.
In a new file place the following:
namespace Namespace.Of.Your.Linq.Classes
{
public partial class Listing
{
public bool IsActive()
{
if(this.Approved==true && this.Deleted==false)
return true;
else
return false;
}
}
}
Since the Listing object (x in your lambda) is just an object, and Linq to SQL defines the generated classes as partial, you can add functionality (properties, methods, etc) to the generated classes using partial classes.
I don't believe the above will be rendered into the SQL query. If you want to do all the logic in the SQL Query, I would recommend making a method that calls the where method and just calling that when necessary.
EDIT
Example:
public static class DataManager
{
public static IEnumerable<Listing> GetActiveListings()
{
using (MyLinqToSqlDataContext ctx = new MyLinqToSqlDataContext())
{
return ctx.Listings.Where(x => x.Approved && !x.Deleted);
}
}
}
Now, whenever you want to get all the Active Listings, just call DataManager.GetActiveListings()
public static class ExtensionMethods
{
public static bool IsActive( this Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
}
Late to the party here, but yet another way to do it that I use is:
public static IQueryable<Listing> GetActiveListings(IQueryable<Listing> listings)
{
return listings.Where(x => x.Approved && !x.Deleted);
}
and then
var activeListings = GetActiveListings(ctx.Listings);

Can you explain this thing about encapsulation?

In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:
That private member variables were
private to the instance and not the
class.
(Link)
I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?
public class Example {
private int a;
public int getOtherA(Example other) {
return other.a;
}
}
Like this. As you can see private doesn't protect the instance member from being accessed by another instance.
BTW, this is not all bad as long as you are a bit careful.
If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.
Here's the equivalent of Michael Borgwardt's answer for when you are not able to access the private fields of the other object:
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return other.valueEquals(this.value); // <------------
}
#Override // This method would probably also be declared in an interface
public boolean valueEquals(int oValue) {
return this.value == oValue;
}
}
Nowadays this is familiar to Ruby programmers but I have been doing this in Java for a while. I prefer not to rely on access to another object's private fields. Remember that the other object may belong to a subclass, which could store the value in a different object field, or in a file or database etc.
Example code (Java):
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return this.value == other.value; // <------------
}
}
If the assumption "private member variables are private to the instance" were correct, the marked line would cause a compiler error, because the other.value field is private and part of a different object than the one whose equals() method is being called.
But since in Java (and most other languages that have the visibility concept) private visibility is per-class, access to the field is allowed to all code of the MutableInteger, irrelevant of what instance was used to invoke it.