我正在尝试为其编写单元测试用例的 Controller 如下 -
@RequestMapping("${rest.base.path}/plugin")
public class Controller {
.
.
.
}
单元测试用例已设置 -
@RunWith(MockitoJUnitRunner.class)
public class ControllerTest {
@Autowired
private MockMvc mvc;
@InjectMocks
Controller dataController;
@Mock
PluginService pluginService;
@Test
public void createFiles() throws Exception {
this.mvc = MockMvcBuilders.standaloneSetup(dataController).build();
mvc.perform(MockMvcRequestBuilders.get("/dc/plugin")
.contentType(MediaType.APPLICATION_JSON));
}
在运行单元测试时,它无法解析占位符 ${rest.base.path},因为我没有加载 Spring 上下文。我尝试设置 System.setProperty("rest.base.path", "/api") 但没有成功。无论如何,我可以在不删除 @RunWith(MockitoJUnitRunner.class) 的情况下为该占位符赋值吗?
最佳答案
这里的关键是自己调用StandaloneMockMvcBuilder.addPlaceholderValue来填充占位符
如文档所述:
In a standalone setup there is no support for placeholder values embedded in request mappings. This method allows manually provided placeholder values so they can be resolved.
所以,下面的简单片段应该适合你
public class TestController {
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(new Controller()).addPlaceHolderValue("rest.base.path", "dc")
.setControllerAdvice(new ExceptionMapper())
.setMessageConverters(new MappingJackson2HttpMessageConverter(new ExtendedObjectMapper())).build();
}
@Test
public void testGet() throws Exception {
mockMvc.perform(get("/dc/plugin").accept(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk());
}}
当然,您可以实现相同的 Autowiring 您的 Controller 。
关于java - 无法解析 Mockito 单元测试中的占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43992597/