Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Spring Boot 使用 Mockito 进行单元测试

Spring Boot 单元测试 大约 2438 字

示例

@ExtendWith({MockitoExtension.class})
public class HelloServiceTests {

    @InjectMocks
    private HelloService helloService = new HelloServiceImpl();

    @Mock
    private UserMapper userMapper;

    // @Spy
    // private HiService hiService = new HiServiceImpl();

    @Mock
    private HiService hiService = new HiServiceImpl();

    // @Spy
    // private HiService hiService;

    @BeforeEach
    public void init() {
        System.out.println("init");
        User mockUser = new User();
        mockUser.setId(2);
        Mockito.when(userMapper.getUserById(1)).thenReturn(mockUser);
    }

    // @BeforeAll 必须是 static 方法
    @BeforeAll
    public static void beforeAll() {
        System.out.println("beforeAll");
    }

    // @AfterAll 必须是 static 方法
    @AfterAll
    public static void afterAll() {
        System.out.println("afterAll");
    }

    @Test
    @DisplayName("测试接口1")
    public void test1() {
        Response response = helloService.sayHello(1);

        Assertions.assertEquals(2, ((User) response.getData()).getId());

    }

    @Test
    @DisplayName("测试接口2")
    public void test2() {
        Response response = helloService.sayHello(1);

        Assertions.assertNotEquals(3, ((User) response.getData()).getId());

    }

}

public interface HelloService {

    Response sayHello(int id);

}

@Service
public class HelloServiceImpl implements HelloService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private HiService hiService;

    @Override
    public Response sayHello(int id) {
        System.out.println("HelloServiceImpl sayHello");
        hiService.sayHi();
        User user = userMapper.getUserById(id);
        return Response.builder().data(user).build();
    }
}

@Mapper
public interface UserMapper {

    @Select("select * from t_user where id = #{id}")
    User getUserById(@Param("id") int id);

}

public interface HiService {

    int sayHi();
}

@Service
public class HiServiceImpl implements HiService {
    @Override
    public int sayHi() {
        System.out.println("HiServiceImpl sayHi");
        return 100;
    }
}

@InjectMocks

需要被单元测试的类,该类中包含了其他依赖注入的组件,使用@InjectMocks表示其他依赖注入的组件是使用@Mock模拟的代理组件,不会走真实的方法。

@Mock

模拟的组件,通常是标注于@InjectMocks中注入的组件。会被代理,单元测试时不走真实方法。

比如模拟@Repository数据库访问对象,这样可以在单元测试时不链接数据库。

@Spy

真实对象,会走真实的方法。

注意:如果标注的是接口类型的组件,需要显示的new出实现类对象,否则@Spy的作用和@Mock一致。

MockitoExtension

@ExtendWith({MockitoExtension.class})表示使用Mockito功能

阅读 115 · 发布于 2022-10-18

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批