greghaskins / spectrum

A BDD-style test runner for Java 8. Inspired by Jasmine, RSpec, and Cucumber.
MIT License
145 stars 23 forks source link

Allow Spring @Autowired dependency injections and Spring Boot integration #99

Closed zifnab87 closed 7 years ago

zifnab87 commented 7 years ago

In case other users find it interesting you could include that in your Documentation:

I have created a BDDTest class that runs with Spectrum.java and also initializes Spring ApplicationContext

@RunWith(Spectrum.class)
@Ignore
@SpringBootTest
public class BDDTest {

    //global autowired objects
    @Autowired
    protected DbC conf;

    @Before
    public void beforeTest() {
        // do stuff
    }
    @After
    public void afterTest() {
        // do stuff
    }

    private TestContextManager testContextManager;

    public BDDTest() {
        try {
            this.testContextManager = new TestContextManager(getClass());
            this.testContextManager.prepareTestInstance(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

classes that are BDD-style can extend BDDTest like that:

public class AttributeControllerTest extends BDDTest {
    @Autowired
    private IAttributeService attributeService;
    private MockMvc mockMvc;

    {
        beforeAll(() -> {
            this.graph = graphService.getGraph();
            mockMvc = MockMvcBuilders
                    .standaloneSetup(new AttributeController(attributeService))
                    .setControllerAdvice(new GlobalExceptionHandler())
                    .build();
        });

        describe("after creation of attribute", () -> {
            Attribute storedAttribute = attributeService.storeAndFetch(new Attribute());

            describe( "fetchByUuid", () -> {
                it("should return 200", () -> {
                    mockMvc.perform(get("/api/attribute/" + storedAttribute.getUuid())).andExpect(status().isOk());
             });
        });
   }
}

Haven't tried it yet but constructor Dependency Injection using @Autowired should work too

Hope someone finds this helpful!

rkawala commented 7 years ago

Have a look at https://github.com/cloudfoundry-incubator/credhub. We've been using Spectrum to write Spring tests for almost a year, and now the project is open source so we can share this. There's probably a better way to do it, but it's worked for us so far.

ashleyfrieze commented 7 years ago

There are limitations of this approach which are overcome by the junitMixin feature that is in the latest version of Spectrum. Please see the docs and post any questions on this thread.

ashleyfrieze commented 7 years ago

I suggest we close this as I believe junitMixin and the native @Rule support should now render it obsolete.