gpt4 book ai didi

java - 带有属性值请求映射的 Spring Boot REST Controller 测试

转载 作者:搜寻专家 更新时间:2023-11-01 03:35:25 26 4
gpt4 key购买 nike

关于 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 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()"
}

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

java.lang.IllegalArgumentException:无法解析字符串值“${base.url}”中的占位符“base.url”

我也尝试过以下方法,但有不同的异常(exception):

  • @IntegrationTest 测试,
  • @WebAppConfiguration,
  • 使用webApplicationContext构建MockMVC
  • 在测试中 Autowiring RESTController
  • 在 SpringContextConfigTest 类中手动定义 REST Controller Bean

和其他各种组合,但似乎没有任何效果。那么我该如何继续才能让它发挥作用呢?我认为这是两个不同配置类的上下文配置问题,但我不知道如何解决它或如何“正确”地解决它。

最佳答案

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

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

关于java - 带有属性值请求映射的 Spring Boot REST Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33410962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com