3

I try to start unit testing a mid size Xtext project.

The generator currently relies on some external resources that I would like to mock inside my test. Thus, I inject the needed object via @Inject into the Generator class.

e.g in pseudocode:

class MyGenerator implements IGenerator{

@Inject
ExternalResourceInterface resourceInterface;

...

}

I create the actual binding inside the languages RuntimeModule:

class MyRuntimeModule{
...
    @Override
    public void configure(Binder binder) {
        super.configure(binder);

        binder.bind(ExternalResourceInterface .class).to(ExternalResourceProductionAcess.class);
    }
...
}

This works fine for the production environment.

However, in the generator test case, I would like to replace the binding with my mocked version, so that the following call to the CompilationTestHelper uses the mock:

    compiler.assertCompilesTo(dsl, expectedJava);

Question:

Where do I tell guice/Xtext to bind the injection to the mock?

Stefan Winkler
  • 3,871
  • 1
  • 18
  • 35
lwi
  • 1,682
  • 12
  • 21

1 Answers1

5

If you annotate your test case with RunWith and InjectWith, your test class will be injected via a specific IInjectorProvider implementation.

If that injector provider uses a custom module (like you have shown), the test case gets injected using that configuration. However, you have to make sure you use this injector throughout the test code (e.g. you do not rely on a registered injector, etc.).

Look for the following code as an example (have not compiled it, but this is the base structure you have to follow):

@RunWith(typeof(XtextRunner))
@InjectWith(typeof(LanguageInjectorProvider))
public class TestClass {

@Inject
CompilationTestHelper compiler

 ...
}
Zoltán Ujhelyi
  • 13,788
  • 2
  • 32
  • 37
  • Thanks for the answer. When using the generated InjectorProvider, my custom module is loaded. However, as the InjectorProvider uses MyRuntimeModule for binding the ExternalResourceProductionAccess is loaded and not my mock. My attempt to write a custom InjectorProvider results in XText not loading its injected resources. – lwi Nov 11 '16 at 12:01
  • A few years ago I customized an InjectorProvider generated by the Xtext generator in VIATRA. Maybe you could have a look at it: http://git.eclipse.org/c/viatra/org.eclipse.viatra.git/tree/query/tests/org.eclipse.viatra.query.patternlanguage.emf.tests/src/org/eclipse/viatra/query/patternlanguage/emf/tests/EMFPatternLanguageInjectorProvider.java – Zoltán Ujhelyi Nov 11 '16 at 15:16