java - 无法解析 Mockito 单元测试中的占位符

标签 java spring unit-testing spring-boot mockito

我正在尝试为其编写单元测试用例的 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/

相关文章:

java - Spring Boot 禁用 Actuator root

java - Spring Boot 示例 RESTful 服务在创建新包后将无法工作

r - 未找到 devtools::test 对象

unit-testing - 如何对事件是否执行 segue 进行单元测试

java - 错误 : cannot access Task class file for bolts

Spring-MVC 3.1 : How to map URLs with a trailing slash?

java - 添加两个 double 值导致值等于 java 中的第二个 double 值

unit-testing - 在 LARGE 项目上启动 UnitTesting

java - 输入指令并使用ArrayList逆序打印出来

java - ${} 模板变量有什么作用?