繁体   English   中英

使用属性值的RequestMapping进行Spring Boot REST控制器测试

[英]Spring Boot REST Controller Test with RequestMapping of Properties Value

关于Spring Boot REST Controller的单元测试,我遇到了@RequestMapping和应用程序属性的问题。

@RestController
@RequestMapping( "${base.url}" )
public class RESTController {
    @RequestMapping( value = "/path/to/{param}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
    public String getStuff( @PathVariable String param ) {
        // implementation of stuff
    }
}

我正在使用应用程序的几个配置文件,因此我有几个application-{profile}.properties文件。 在每个文件中, base.url属性值已设置并存在。 我还有一个不同的Spring Context配置用于测试,只有一个Bean与高效版本不同。

使用JUNit和Mockito / RestAssured,我的单元测试如下所示:

@ActiveProfiles( "dev" )
@RunWith( SpringJUnit4ClassRunner.class )
@SpringApplicationConfiguration( classes = SpringContextConfigTest.class )
public class RESTControllerTest {

private static final String SINGLE_INDIVIDUAL_URL = "/query/api/1/individuals/";

@InjectMocks
private RESTController restController;

@Mock  
private Server mockedServer; // needed for the REST Controller to forward

@Before
public void setup() {
  RestAssuredMockMvc.mockMvc( MockMvcBuilders.standaloneSetup(restController).build() );
 MockitoAnnotations.initMocks( this );
}

@Test
public void testGetStuff() throws Exception {
  // test the REST Method "getStuff()"
}

问题是,REST控制器在生产模式下启动时正在运行。 在单元测试模式下,在构建mockMvc对象时,未设置${base.url}值并抛出异常:

java.lang.IllegalArgumentException: Could not resolve placeholder 'base.url' in string value "${base.url}"

我也尝试过以下方法,但有不同的例外:

  • @IntegrationTest on Test,
  • @WebAppConfiguration
  • 使用webApplicationContext构建MockMVC
  • 在测试中自动装配RESTController
  • 手动定义SpringContextConfigTest类中的REST控制器Bean

和其他各种组合,但似乎没有任何作用。 那么我该如何继续,以使其工作? 我认为这是两个不同的配置类的Context配置问题,但我不知道如何解决它或如何“正确”。

您需要在独立设置中添加占位符值 -

mockMvc=MockMvcBuilders.standaloneSetup(youController).addPlaceholderValue(name, value);

似乎在非生产模式下,属性占位符无法解析。 您肯定想要查看PropertyPlaceholderConfigurer文档页面。

这个答案也可以为实施提供一些帮助。

我使用一个application.yml文件而不是profile-properties解决了这个问题。 yml文件使用default配置文件的标准定义,该定义在文件顶部定义。

#default settings. these can be overriden for each profile.
#all these settings are overriden by env vars by spring priority
rest:
  api:
    version: 1
base:
   url: /query/api/${rest.api.version}
---
spring:
   profiles: dev
---
spring:
   profiles: production
main:
  show_banner: true
---
spring:
   profiles: test
base:
   url: /query/override/default/value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM