How to test Classes with @ConfigurationProperties and @Autowired

后端 未结 5 922
感情败类
感情败类 2020-12-09 07:52

I want to test small parts of the application that rely on properties loaded with @Autowired and @ConfigurationProperties. I am looking for a solut

5条回答
  •  佛祖请我去吃肉
    2020-12-09 08:15

    Unit test

    To avoid having to load a Spring context, we can use the Binder class, which is also used internally by Spring anyway.

    // A map of my properties.
    Map properties = new HashMap<>();
    properties.put("my-prefix.first-property", "foo");
    properties.put("my-prefix.second-property", "bar");
    
    // Creates a source backed by my map, you can chose another type of source as needed.
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties)
    
    // Binds my properties to a class that maps them.
    Binder binder = new Binder(source);
    BindResult result = binder.bind("my-prefix", MyConfiguration.class);
    
    // Should return true if bound successfully.
    Assertions.assertTrue(result.isBound);
    
    // Asserts configuration values.
    MyConfiguration config = result.get();
    Assertions.assertEquals("foo", config.getFirstProperty());
    Assertions.assertEquals("bar", config.getSecondProperty());
    

提交回复
热议问题