【SpringBoot】mockito+junit 单元测试

1.POM 引入以下依赖

      <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>
     <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <version>2.5.2version>
            <scope>testscope>
        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)

你可能感兴趣的:(spring,boot,单元测试)