spring boot 测试用例

 junit 是一个面向于研发人员使用的轻量的测试模块,适合做单元测试。而testng百度后发现更强大,可以做功能测试,但对于我这种RD,貌似junit足沟了呢!

java Mock PowerMock、jmockit 模拟包非常优秀,我目前选型学会一个就不错了,不做评价,我学的powermock,据说jmockit更强大。但是powermock貌似继承了旧的easymock和jmock,所以用的人比较大(个人理解)。

 

对于junit测试的几个注解

@RunWith

@Before 

@Test

@After

 

powerMock注解

@Mock

@InjectMocks

 

@RunWith 表示运行方式,@RunWith(JUnit4TestRunner)、@RunWith(SpringRunner.class),@RunWith(PowerMockRunner.class) 三种运行方式,分别在不同的场景中使用。

@Before是 @Test运行之前调用的方法,可以做初始化操作

@Test  是测试用例的单元

@After 执行完测试用例需要执行的清理工作

@Mock  有点类似Autowired注解,而@Mock注解是自动实现模拟对象,而并非Bean实例创建

@InjectMocks 实现对@Mock注解的对象注入到当前对象中,通过MockitoAnnotations.initMocks(this);实现

 

package aa;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.mockito.Matchers.any;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


@RunWith(PowerMockRunner.class)
@SpringBootTest(classes = MainApplication.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PowerMockIgnore("javax.management.*") 
public class moreTest {

    @Mock
    TService tService;
    @InjectMocks
    TController controller;
    @Autowired
    private WebApplicationContext ctx;
    private MockMvc mvc;

    @Before
    public void before() throws Exception {

        MockitoAnnotations.initMocks(this);
//如果简单mock一个请求可以使用这个,但是要模拟注入,还是按下面的方式实现controller比较好
//        mvc = MockMvcBuilders.webAppContextSetup(ctx).build();
        mvc = MockMvcBuilders.standaloneSetup(controller).build();
//        taskPackageService=PowerMockito.mock(TService);
        PowerMockito.when(tService.queryMethod(any(ParameClass.class)))
                .thenReturn(88);
    PowerMockito.whenNew(TService.class).withNoArguments().thenReturn(tService);
    }

    @Test
    public void searchTest() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/welcome").header("User-Agent", "xx")
                .param("page", "1")
        ).andExpect(status().isOk()).andDo((MvcResult result) -> {
            System.out.println(result.getResponse().getContentAsString());
        });
    }

}

 

posted @ 2018-11-12 17:08  阿旭^_^  阅读(4316)  评论(0编辑  收藏  举报