mch*_*chr 5 java rest spring unit-testing spring-boot
关于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
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用该应用程序的多个配置文件,因此有多个application-{profile}.properties文件。在每个文件中,base.url都会设置并显示属性值。我还有一个不同的Spring Context Configuration进行测试,只有一个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()"
}
Run Code Online (Sandbox Code Playgroud)
问题是,在生产模式下启动时,REST控制器正在运行。在单元测试模式下,${base.url}构建mockMvc对象时,未设置该值,并且引发了异常:
java.lang.IllegalArgumentException: Could not resolve placeholder 'base.url' in string value "${base.url}"
我还尝试了以下方法,但有不同的例外:
@IntegrationTest 经过测试@WebAppConfiguration, webApplicationContext来构建MockMVC和其他各种组合,但似乎无济于事。那么,如何使其继续工作才能继续下去?我认为这是使用两个不同的配置类的上下文配置问题,但我不知道如何解决它或如何“正确”地完成它。
application.yml我通过使用一个文件而不是配置文件属性解决了这个问题。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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3003 次 |
| 最近记录: |