下面的代码是为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注入到我的控制器中的。我尝试了几种方法,但都没有成功。下面的代码由于MVC404错误而失败,因为我猜我使用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不会被我的静态类替换。
有人能帮帮我吗?关于注解的文档非常混乱。
发布于 2017-02-20 22:35:16
阅读评论,下面是解决方案:
@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
}
}https://stackoverflow.com/questions/42345003
复制相似问题