sts-Junit学习篇之mockMvc

1.sts自动生成测试类

选择要生成测试类的文件,右键->new->Junit test case或者右键->new->other->Java->junit test case

2.类名上添加的注解

(1)首先测试Controller类时,在类名上加入注解@RunWith和@WebMvcTest,@ActiveProfiles("test")

@RunWith(SpringRunner.class)

@WebMvcTest( {LogComponent.class, MessageConfig.class, MessageComponent.class,
    CloseController.class})

其中:LogComponent.class, MessageConfig.class, MessageComponent.class,
    CloseController.class为测试CloseController类时需要的类,CloseController.class为启动类,此处名字与需要测试的controller名字一致。

(2)测试Service类时,在类名上加入注解@RunWith和@SpringBootTest,@ActiveProfiles("test")

@RunWith(SpringRunner.class)

@SpringBootTest(classes = {LogComponent.class, MessageConfig.class, MessageComponent.class,
    SessionService.class})

(1)关于区别@WebMvcTest和@SpringBootTest :

@SpringBootTest注释告诉Spring Boot去寻找一个主配置类(例如一个带@SpringBootApplication),并使用它来启动Spring应用程序上下文。SpringBootTest加载完整的应用程序并注入所有可能很慢的bean。

@WebMvcTest - 用于测试控制器层,您需要使用模拟对象提供所需的剩余依赖项。

补充:

@WebMvcTest - for testing the controller layer

@JsonTest - for testing the JSON marshalling and unmarshalling

@DataJpaTest - for testing the repository layer

@RestClientTests - for testing REST clients

(2)关于@ActiveProfiles()

public @interface ActiveProfiles
ActiveProfiles是类级注释,用于声明在加载测试类ApplicationContext时应使用哪些活动 Bean 定义配置文件

此注释可用作元注释,以创建自定义组合注释

详细了解:https://spring.io/

 

3.自动注入对象

(1)针对自己的实际业务来注入对象,比如controller,service里依赖了其他某个qitaservice时,则

@MockBean
 private qitaService qitaService;

(2)@Autowired

private MockMvc mockMvc;//引入MockMvc对象,我们在这里实例化mockmvc对象,这样后面就可以操作他了。

(3)@Rule
    public OutputCapture capture = new OutputCapture();//规则,OutputCapture是一个JUnit Rule,用于捕获System.out和System.err输出。只需简单的将捕获声明为一个@Rule,并使用toString()断言。

具体用法:

@Test
    public void test() {
       Assert.assertThat(capture.toString(), containsString("suibianxiede"));
    }

 (4)   @Before和@After

@Before
    public void before() throws Exception {
    }

    @After
    public void after() throws Exception {
    }

4.每个方法上写@Test

例如测试controller中的方法

@Test
    public void testDeleteSession_ok() throws Exception {
      this.mockMvc.perform(post("url"))//url you want to post
                .andDo(print()).andExpect(status().is("status"));//status you want to get
        Assert.assertThat(capture.toString(), containsString("suibianxiede"));            
    }

发布了11 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/LYW_lyw/article/details/104477289
今日推荐