mockito在spring boot中的使用

本文详细介绍了如何在Spring Boot项目中使用Mockito进行对象模拟,包括直接mock、@Mock注解、MockitoJUnitRunner和MockitoRule的四种方法,并通过示例展示了如何设置预期行为和验证调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mockito在spring boot中的使用

1. 方法一:

直接使用mockito提供的mock方法即可以模拟一个服务实例。再结合when/thenReturn等语法完成方法的模拟实现。

@SpringbootTest
public class TokenServiceTest{
    private TokenService tokenService ;
    @BeforeEach
    public void before(){
         tokenService = mock(TokenService.class);
    }
    @Test 
    public void test1(){
        Token token = new Token(1,"test");
        when(tokenService.getTokenById(1)).thenReturn();
        System.out.println(tokenService.getTokenById(1).getToken());
        verify(tokenService.getTokenById(1)); //判断是不是被调用
    } 
}

2. 方法二

使用@Mock注解来Mock对象时的第一种实现,即使用MockitoAnnotations.initMocks(testClass)。

@SpringbootTest
public class TokenServiceTest{
    @Mock
    private TokenService tokenService ;
    @BeforeEach
    public void before(){
         MockitoAnnotations.initMocks(this);
    }
    @Test 
    public void test1(){
        Token token = new Token(1,"test");
        when(tokenService.getTokenById(1)).thenReturn();
        System.out.println(tokenService.getTokenById(1).getToken());
        verify(tokenService.getTokenById(1)); //判断是不是被调用
    } 
}
3. 方法三

z在测试用例上加上@RunWith(MockitoJUnitRunner.class)这个注解后。就可以自由的使用@Mock来Mock对象。注:JUnit4

@RunWith(MockitoJUnitRunner.class)
@SpringbootTest
public class TokenServiceTest{
    @Mock
    private TokenService tokenService ;
        
    @Test 
    public void test1(){
        Token token = new Token(1,"test");
        when(tokenService.getTokenById(1)).thenReturn();
        System.out.println(tokenService.getTokenById(1).getToken());
        verify(tokenService.getTokenById(1)); //判断是不是被调用
    } 
}
4.方法四

使用MockitoRule,对象的访问级别必须是public。注:JUnit4

@RunWith(JUnit4.class)
@SpringbootTest
public class TokenServiceTest{
    @Rule
    public MockitoRule rule = MockitoJUnit.rule();
    @Mock
    private TokenService tokenService;
        
    @Test 
    public void test1(){
        Token token = new Token(1,"test");
        when(tokenService.getTokenById(1)).thenReturn();
        System.out.println(tokenService.getTokenById(1).getToken());
        verify(tokenService.getTokenById(1)); //判断是不是被调用
    } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值