Spring mvc 测试Spring Mvc控制器并注入静态类

Spring mvc 测试Spring Mvc控制器并注入静态类,spring-mvc,spring-boot,junit,Spring Mvc,Spring Boot,Junit,以下代码是为Mvc控制器编写JUnit测试的标准方法 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ApplicationTestCassandra.class) @WebAppConfiguration public class TestControllerTests { @Autowired private WebApplicationContext webApplicatio

以下代码是为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不会被我的静态类替换


谁能帮帮我吗?有关注释的文档非常混乱。

请阅读注释,以下是解决方案:

@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
        }
}

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