Spring Context Test With Just One Bean

For starters, reading the documentation first (e.g., the JavaDoc linked below in this answer) is a recommend best practice since it already answers your question.

If I understand correctly the class that I reference is supposed to be a Configuration class, not a regular spring service bean or component for example.

Is that right?

No, that's not completely correct.

Classes provided to @ContextConfiguration are typically @Configuration classes, but that is not required.

Here is an excerpt from the JavaDoc for @ContextConfiguration:

Annotated Classes

The term annotated class can refer to any of the following.

  • A class annotated with @Configuration
  • A component (i.e., a class annotated with @Component, @Service, @Repository, etc.)
  • A JSR-330 compliant class that is annotated with javax.inject annotations
  • Any other class that contains @Bean-methods

Thus you can pass any "annotated class" to @ContextConfiguration.

Or is this indeed a valid way to achieve this goal?

It is in fact a valid way to achieve that goal; however, it is also a bit unusual to load an ApplicationContext that contains a single user bean.

Regards,

Sam (author of the Spring TestContext Framework)


It is definitely a reasonable and normal thing to only test a single class in a unit test.

There is no problem including just one single bean in your test context. Really, a @Configuration is (typically) just a collection of beans. You could hypothetically create a @Configuration class just with MyTestBean, but that would really be unnecessary, as you can accomplish doing the same thing listing your contextual beans with @ContextConfiguration#classes.

However, I do want to point out that for only testing a single bean in a true unit test, best practice ideally leans towards setting up the bean via the constructor and testing the class that way. This is a key reason why the Spring guys recommend using constructor vs. property injection. See the section entitled Constructor-based or setter-based DI of this article, Oliver Gierke's comment (i.e. head of Spring Data project), and google for more information. This is probably the reason you're getting a weird feeling about setting up the context for the one bean!