【问题标题】:Test Spring Mvc controller and inject static class测试 Spring Mvc 控制器并注入静态类
【发布时间】:2017-02-20 12:47:47
【问题描述】:

以下代码是为 Mvc 控制器编写 JUnit 测试的标准方法。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationTestCassandra.class)
@WebAppConfiguration
public class TestControllerTests {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testupTimeStart() throws Exception {
        this.mockMvc.perform(get("/uptime"))
                .andExpect(status().isOk());

    }
}

这很好用,但我想用一个特殊的类替换一个自动装配的类来进行测试。 CassandraSimpleConnection 类是通过我的控制器中的@Autowired 注入的。 我尝试了几种方法,但没有运气。 以下代码由于 Mvc 404 错误而失败,因为我猜我的带有 REST 接口的应用程序根本没有运行。

@RunWith(SpringJUnit4ClassRunner.class)
//ApplicationTestCassandra is SpringBoot application startpoint class with @SpringBootApplication annotation
//@ContextConfiguration(classes = ApplicationTestCassandra.class, loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)//, classes = {ApplicationTestCassandra.class})
@WebAppConfiguration
public class TestControllerTests {

    @Service
    @EnableWebMvc
    @ComponentScan(basePackages={"blabla.functionalTests"})
    static class CassandraSimpleConnection {

        public Metadata testConnection(TestConfiguration configuration) {
            Metadata metadata = null;
            // return metadata;

            throw new RuntimeException("Could not connect to any server");
        }
    }

如果我使用

@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class,    classes = {ApplicationTestCassandra.class})

CassandraSimpleConnection 没有被我的静态类替换。

有人可以帮帮我吗?关于注释的文档相当混乱。

【问题讨论】:

  • 为什么要这样。它是一项服务而不是配置,因此永远不会被检测到。在非@Configuration 类上添加@EnableWebMvc@ComponentScan 也没什么用。
  • 好的,谢谢。运行测试时如何替换服务类?模拟 CassandraSimpleConnection 的最简单方法是什么?我应该模拟 com.datastax.driver.core.Cluster 吗?
  • 您可以使用 @Bean for CassandraSimpleConnection 在测试用例中“覆盖”您的 bean
  • 非常感谢。正是我想要的。

标签: spring-mvc spring-boot junit


【解决方案1】:

阅读 cmets,这是解决方案:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MyApplication.class })
public class MyTests {

        @MockBean
        private MyBeanClass myTestBean;

        @Before
        public void setup() {
             ...
             when(myTestBean.doSomething()).thenReturn(someResult);
        }

        @Test
        public void test() {
             // MyBeanClass bean is replaced with myTestBean in the ApplicationContext here
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    相关资源
    最近更新 更多