【SpringBoot】mockito+junit 单元测试

1.POM 引入以下依赖

      <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.5.2</version>
            <scope>test</scope>
        </dependency>

2.Service层接口单元测试示例

package xxx.xxx.xxx;

import org.apache.commons.collections.CollectionUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Arrays;



@RunWith(MockitoJUnitRunner.class)
@Slf4j
class CommonServiceImplTest {


    @Autowired
    @InjectMocks
    CommonServiceImpl commonService;

    @Mock
    ServiceA  serviceA;

    @Mock
    ServiceB  servieB;



    private QueryBo queryBO;



    @BeforeEach
    public void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void getSourceCodeMap() {
        queryBO = new QueryBO();
        queryBO.setFieldA("A");
        queryBO.setFieldB("B"); 

        CommonEntity entity = new CommonEntity ();
        entity.setField1("1");
        entity.setField2("2");
        Mockito.when(serviceA.list(queryBO)).thenReturn(Arrays.asList(new CommonEntity []{entity}));
        Assert.assertNotNull(commonService.getSourceCodeMap());
    }

CommonServiceImpl 在方法getSourceCodeMap()调用了ServiceA的方法list(QueryBO queryBo)