MockitoTest 单元测试

package com.yiautos.psf.order.service.impl;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

import java.util.ArrayList;
import java.util.List;


public class MockitoTest {


    @Test
    public void testBehavior() {
        //构建mock数据
        List<String> list = Mockito.mock(List.class);
        list.add("1");
        list.add("2");

        System.out.println(list.get(0)); // 会得到null ,前面只是在记录行为而已,没有往list中添加数据

        Mockito.verify(list).add("1"); // 正确,因为该行为被记住了
        Mockito.verify(list).add("3");//报错,因为前面没有记录这个行为

    }

    @Test
    public void testStub() {
        List<Integer> l = Mockito.mock(ArrayList.class);

        Mockito.when(l.get(0)).thenReturn(10);
        Mockito.when(l.get(1)).thenReturn(20);
        Mockito.when(l.get(2)).thenThrow(new RuntimeException("no such element"));

        Assert.assertEquals(10, (int) l.get(0));
        Assert.assertEquals(20, (int) l.get(1));
        Assert.assertNull(l.get(4));
        l.get(2);
    }

    @Test
    public void testSpy() {
        List<String> spyList = Mockito.spy(ArrayList.class);

        spyList.add("one");
        spyList.add("two");

        Mockito.verify(spyList).add("one");
        Mockito.verify(spyList).add("two");

        Assert.assertEquals(2, spyList.size());

        Mockito.doReturn(100).when(spyList).size();
        Assert.assertEquals(100, spyList.size());
    }

    @Test
    public void testVoidStub() {
        List<Integer> l = Mockito.mock(ArrayList.class);
        Mockito.doReturn(10).when(l).get(1);
        Mockito.doThrow(new RuntimeException("you cant clear this List")).when(l).clear();

        Assert.assertEquals(10, (int) l.get(1));
        l.clear();
    }

    @Test
    public void testMatchers() {
        List<Integer> l = Mockito.mock(ArrayList.class);
        Mockito.when(l.get(Mockito.anyInt())).thenReturn(100);

        Assert.assertEquals(100, (int)l.get(999));
    }
}

 mock token

  @Mock
    private HttpServletRequest request;

    @Before
    public void init() {
        BladeUser bladeUser = new BladeUser();
        bladeUser.setUserId("1");
        //部门研发部
        bladeUser.setDeptId("2");
        Mockito.when(request.getRequestURI()).thenReturn("");
        Mockito.when(request.getAttribute("_BLADE_USER_REQUEST_ATTR_")).thenReturn(bladeUser);
        ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(request);
        RequestContextHolder.setRequestAttributes(servletRequestAttributes);
    }

  

posted @ 2022-04-18 11:14  八英里  阅读(77)  评论(0编辑  收藏  举报