【问题标题】:Spring context compile time validationSpring 上下文编译时验证
【发布时间】:2015-12-22 10:34:13
【问题描述】:

是否有任何工具或 maven 插件可以在编译时或 maven 构建执行期间验证 Spring 上下文?

我知道在没有应用程序启动的情况下检查上下文的完全正确性并非易事,但检查一些琐碎的情况会很好,例如,如果您在 xml 上下文中定义一个 bean,那么 bean 类必须是存在于类路径中。

【问题讨论】:

  • 您应该在 Maven 测试阶段为此使用测试。
  • 是的,希望在 Maven 构建阶段执行它,问题是 - 究竟要执行什么。 @luboskrnac 的例子看起来不错,我会试试那个。

标签: java spring maven spring-mvc testing


【解决方案1】:

每个Spring Guide 都包含这样的健全性测试。

对于 Spring MVC 应该使用 MockMvc 测试。要验证 Spring 配置是否正常,您可以创建完整的上下文并针对 URL 触发请求,还包括验证 + 所有 Spring 接线。此类测试在 test maven 阶段执行。

类似这样的:

@WebAppConfiguration
@ContextConfiguration(classes = RestApplication.class)
public class RestApplicationContextTest extends
    AbstractTestNGSpringContextTests {

  private static final String FULL_USER_URL = "http://localhost:10403/users";
  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext webApplicationContext;

  @BeforeMethod
  public void init() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  }

  private static String createTestRecord(int identifier) {
    String testingRecordString =
        "{\"email\": \"user%d@gmail.com\", \"name\": \"User%d\"}";
    return String.format(testingRecordString, identifier, identifier,
        identifier);
  }

  @Test
  public void testPost() throws Exception {
    // GIVEN
    String testingRecord = createTestRecord(0);

    // WHEN
    // @formatter:off
    MvcResult mvcResult = mockMvc.perform(post(FULL_USER_URL)
        .contentType(MediaType.APPLICATION_JSON)
        .content(testingRecord))
        .andReturn();
    // @formatter:on

    // THEN
    int httpStatus = mvcResult.getResponse().getStatus();
    assertEquals(httpStatus, HttpStatus.CREATED.value());
  }
  ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    相关资源
    最近更新 更多