关于 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:无法解析字符串值“${base.url}”中的占位符“base.url”
我也尝试过以下方法,但有不同的例外:
> @IntegrationTest on Test,
> @WebAppConfiguration,
>使用webApplicationContext构建MockMVC
>在测试中自动装配RESTController
>手动在SpringContextConfigTest类中定义REST控制器Bean
和其他各种组合,但似乎没有任何作用.
那么我该如何继续,以使其工作?
我认为这是两个不同的配置类的Context配置问题,但我不知道如何解决它或如何“正确”.
最佳答案 您需要在独立设置中添加占位符值 –
mockMvc=MockMvcBuilders.standaloneSetup(youController).addPlaceholderValue(name, value);