comparison spring-di-playground/src/test/java/de/comline/spring/QualifierTest.java @ 0:64e2ebad3366

Import des plain Spring DI playground
author Dirk Olmes <dirk.olmes@codedo.de>
date Tue, 11 Aug 2020 16:05:44 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:64e2ebad3366
1 package de.comline.spring;
2
3 import static org.hamcrest.MatcherAssert.assertThat;
4 import static org.hamcrest.Matchers.containsString;
5 import static org.hamcrest.Matchers.is;
6 import static org.junit.jupiter.api.Assertions.assertThrows;
7
8 import org.junit.jupiter.api.DisplayName;
9 import org.junit.jupiter.api.Test;
10 import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
11 import org.springframework.context.ConfigurableApplicationContext;
12 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
13
14 import de.comline.spring.model.ActionMovieCatalog;
15 import de.comline.spring.model.ActionMovieLister;
16 import de.comline.spring.model.ComedyMovieCatalog;
17 import de.comline.spring.model.MovieCatalog;
18
19 public class QualifierTest {
20 @Test
21 @DisplayName("Requesting explicit interface type")
22 public void explicitType() {
23 try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ActionMovieCatalog.class, ComedyMovieCatalog.class)) {
24 MovieCatalog action = context.getBean(ActionMovieCatalog.class);
25 assertThat(action.getCategory(), is("Action"));
26 }
27 }
28
29 @Test
30 @DisplayName("Qualifier can be specified at source")
31 public void qualifierAtSource() {
32 // Note how we add multiple interface implementations to the context
33 try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ActionMovieCatalog.class, ComedyMovieCatalog.class, ActionMovieLister.class)) {
34 ActionMovieLister lister = context.getBean(ActionMovieLister.class);
35 assertThat(lister.toString(), containsString("Action"));
36 }
37 }
38
39 @Test
40 @DisplayName("Binding only a single interface implementation")
41 public void singleImplementationOfInterface() {
42 try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ComedyMovieCatalog.class)) {
43 MovieCatalog catalog = context.getBean(MovieCatalog.class);
44 assertThat(catalog.getCategory(), is("Comedy"));
45 }
46 }
47
48 @Test
49 @DisplayName("Multiple implementations of the same interface cannot be injected")
50 public void multipleInterfaceImplementations() {
51 try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(ActionMovieCatalog.class, ComedyMovieCatalog.class)) {
52 assertThrows(NoUniqueBeanDefinitionException.class, () -> {
53 context.getBean(MovieCatalog.class);
54 });
55 }
56 }
57 }