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)); //判断是不是被调用
}
}