Unit tests vs integration tests with Spring

2019-01-21 08:05发布

问题:

I'm working on a Spring MVC project, and I have unit tests for all of the various components in the source tree.

For example, if I have a controller HomeController, which needs to have a LoginService injected into it, then in my unit test HomeControllerTest I simply instantiate the object as normal (outside of Spring) and inject the property:

protected void setUp() throws Exception {
    super.setUp();
    //...
    controller = new HomeController();
    controller.setLoginService( new SimpleLoginService() );
    //...
}

This works great for testing each component as an isolated unit - except now that I have a few dozen classes in the project, after writing a class and writing a successful unit test for it, I keep forgetting to update my Spring MVC context file that does the actual wiring-up in the deployed application. I find out that I forgot to update the context file when I deploy the project to Tomcat and find a bunch of NullPointers from non-wired-up beans.

So, here are my questions:

  1. This is my first Spring project - is it normal to create unit tests for the individual beans, as I have done, and then create a second suite of tests (integration tests) to test that everything works as expected with the actual application context? Is there an established best practice for this?

  2. In addition, how do you separate the unit tests from the integration tests? I have all of the source code in src, the unit tests in test - should there be a 2nd test folder (such as test-integration) for integration test cases?

Since this is my first Spring project, I'm curious how others usually go about doing this sort of thing - and rather than re-invent the wheel I rather ask the rest of the community.

回答1:

I can't speak to being a best practice, but here's what I've done in the past.

Unit tests:

  • Create unit tests for non-trivial beans (ie, most of your Spring related beans)
  • Use Mocks for injected services where practical (ie, most if not all the time).
  • Use a standard naming convention for these tests in the project test directory. Using Test or TestCase as a prefix or suffix to the classname seems to be widely practiced.

Integration Tests:

  • Create an AbstractIntegrationTestCase that sets up a Spring WebApplicationContext for use in intetgration test clases.
  • Use a naming convention for integration tests in the test directory. I've used IntTest or IntegrationTest as a prefix or suffix for these tests.

Set up three Ant test targets:

  1. test-all (or whatever you want to name it): Run Unit and Integration Tests
  2. test: Run Unit tests (just because test seems to be the most common usage for unit testing
  3. test-integration: run the integration tests.

As noted, you can use the naming conventions that make sense for your project.

As to separating unit from integration tests into a separate directory, I don't think it matters as long as the developers and their tools can find and execute them easily.

As an example, the last Java project I worked on with Spring used exactly what is described above, with integration tests and unit tests living in the same test directory. Grails projects, on the other hand, explicitly separate unit and integration test directories under a general test directory.



回答2:

A few isolated points:

Yes, it's a common approach to Spring testing - seperate unit tests and integration tests where the former doesn't load any Spring context.

For your unit tests, maybe consider mocking to ensure that your tests are focussed on one isolated module.

If you're tests are wiring in a ton of dependencies then they aren't really unit tests. They're integration tests where you are wiring of dependencies using new rather than dependency injection. A waste of time and duplicated effort when your production application uses Spring!

Basic integration tests to bring up your Spring contexts are useful.

The @required annotation may help you to ensure you catch required dependencies in your Spring wiring.

Maybe look into Maven which will give you explicit phases to bind your unit and integration tests on to. Maven is quite widely used in the Spring community.



回答3:

A lot of the tedious double-book-keeping with spring goes away if you also switch to a purely annotated regime, where you annotate all your beans with @Component, @Controller, @Service and @Repository. Just add @Autowired to the attributes you need to get injected.

See section 3.11 of the spring reference manual. http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config

On a related note, we have been using the division Unit/Integratrion tests that KenG describe. In my most recent regime we have also introduced a third "class" of tests, "ComponentTests". These run with full spring wiring, but with wired stub implementations (using component-scan filters and annotations in spring).

The reason we did this was because for some of the "service" layer you end up with an horrendous amount of hand-coded wiring logic to manually wire up the bean, and sometimes ridiculous amounts of mock-objects. 100 lines of wiring for 5 lines of test is not uncommon. The component tests alleviate this problem.



回答4:

Use the InitializingBean interface (implements a method "afterPropertiesSet") or specify an init-method for your beans. InitializingBean is typically easier because you don't need to remember to add the init method to your beans.

Use afterPropertiesSet to ensure everything is injected as non-null, if it is null, throw an Exception.



回答5:

When I've created integration tests for web applications, I've put them in a separate directory. They are built using jUnit or TestNG and interact with the system under test using something like Selenium that hits the web pages as if they were users. The cycle would go like this: compile, run unit tests, build the web app, deploy it to a running server, execute the tests, undeploy the app, and report results. The idea is to test the whole system.



回答6:

With regard to running unit tests separately from integration tests, I put all the latter into an integration-test directory and run them using IDE/Ant using an approach like this. Works for me.



回答7:

the difference between unit test and integration test is , unit test does not necessarily load your context, you are focusing on the code which you have written - it works fails fast , that is with and without exceptions, by mocking any depends calls in it. But in case of integration tests , you load context and perform end to end test like actual scenarios.