Mockito单元测试

Posted 全力付出

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mockito单元测试相关的知识,希望对你有一定的参考价值。

Mockito单元测试

Maven依赖

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>2.0.2-beta</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>

普通类mock

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;

public class DataHandlerTest 

    @InjectMocks
    DataHandler                   dataHandler = new DataHandler();

    @Mock
    protected HttpServletRequest  request;

    @Mock
    protected HttpServletResponse response;

    @Before
    public void before() throws Exception 
        MockitoAnnotations.initMocks(this);
    

    @Test
    public void testPrintString() throws Exception 
        JsonResult result = new JsonResult();
        Mockito.doNothing().doAnswer(new Answer() 

            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable 
                return null;
            
        ).when(response).setHeader("Content-Type", "application/json");

        String path = DataHandlerTest.class.getResource("/").getPath() + "dataHandler.txt";
        File file = new File(path);
        if (!file.exists()) 
            file.createNewFile();
        
        PrintWriter writer = new PrintWriter(file);
        Mockito.when(response.getWriter()).thenReturn(writer);
        dataHandler.print(result);

        if (file != null && file.exists()) 
            file.delete();
        
    

静态类mock

@RunWith(PowerMockRunner.class)
@PrepareForTest(ThreadContext.class)
public class CartTest 


    @InjectMocks
    private Cart cart = new Cart();

    @Mock
    ThreadContext threadContext;

    @Mock
    protected HttpServletRequest request;

    @Mock
    protected HttpServletResponse response;

    @Before
    public void before() throws Exception  
        MockitoAnnotations.initMocks(this);
        PowerMockito.mockStatic(ThreadContext.class);

        ThreadContext threadContext2 = new ThreadContext();
        threadContext2.setLoginId("123");

        //Mock当前用户信息 currentUser
        Mockito.when(ThreadContext.getCurrentUser()).thenReturn(threadContext2);

        //Mock response.setHeader方法
        Mockito.doAnswer(new Answer<Object>() 
            public Object answer(InvocationOnMock invocation) 
                Object[] args = invocation.getArguments();
                return "called with arguments: " + args;
            
        ).when(response).setHeader(Mockito.anyString(),Mockito.anyString());

    


   /** 
    * 
    * Method: screen(Context context) 
    * 
    */ 
    @Test
    public void test() throws Exception 
        Map<String, String> map = Maps.newHashMap();
        map.put("Login","test");
        Context context = new MappedContext();

        //Mock request中获取回调函数名的方法
        Mockito.when(request.getParameter(Mockito.any(String.class))).thenReturn("callback");
        cart.screen(context);

    

以上是关于Mockito单元测试的主要内容,如果未能解决你的问题,请参考以下文章

单元测试(mock) 错误org.mockito.Mockito.framework()Lorg/mockito/MockitoFramework;解析

单元测试(mock) 错误org.mockito.Mockito.framework()Lorg/mockito/MockitoFramework;解析

Android单元测试系列-Mock之Mockito

Kotlin&Mockito单元测试在gradle中失败

Mockito单元测试

Mockito一个采用Java编写用于单元测试的Mocking框架