keepcosmos / beanmother

A library for setting up Java objects as test data.
http://beanmother.io
Apache License 2.0
115 stars 23 forks source link

Shared reference between beans? #33

Open dirkredeye opened 5 years ago

dirkredeye commented 5 years ago

Hi!

I want to try this library for testing, but the immediate problem I've run into is that I can't re-use an instance. Essentially I want to do this:

pizza: &pizza
  ingredients:
    - ham
    - cheese
    - pineapple
  name: hawaiian

mario: &mario
  name: Mario
  lunch: *pizza
  dinner: *pizza
  breakfast: *pizza

Except I want a single instance of Pizza. Eg so that mario.lunch == mario.dinner instead of just mario.lunch.equals(mario.dinner)

Is there a built in way I can do this?

dirkredeye commented 5 years ago

At first, I thought I could do this with a custom ScriptHandler that lets me use a function like

pizza: &pizza
  ingredients:
    - ham
    - cheese
    - pineapple
  name: hawaiian

mario: &mario
  name: Mario
  lunch: singleton(pizza)
  dinner: singleton(pizza)
  breakfast: singleton(pizza)

Where I planned to run:

@Override
public Object run(ScriptFragment scriptFragment) {
    String ref = scriptFragment.getArguments().get(0);

    Object singleton = singletons.get(ref);
    if (singleton == null) {
        objectMother.bear(ref, SOME_UNKNOWN_CLASS)
    }
}

But I don't have access to SOME_UNKNOWN_CLASS in this context, so I can't just cache it with a function