/***
* @Type
* @Desc
* @Author Cristal
* @Date 2020/12/30 11:42
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest
public class CommonManagerTest {
@InjectMocks//要测试的类
private CommonManager commonManager = new CommonManagerImpl();
@MockBean//测试的类依赖或使用到的类
private DataMapper DataMapper;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Mock
private ValueOperations<String, String> valueOperations;
@MockBean
private StringRedisTemplate stringRedisTemplate;
@Test
public void testGetMachineLastDate() {
Mockito.when(stringRedisTemplate.opsForValue()).thenReturn(valueOperations);//redisTemplate写法
Mockito.doReturn(new Data()).when(DataMapper).selectOne(Mockito.any(Wrapper.class));//有结果返回写法
commonManager.getDataByDate(LocalDateTime.now());
Mockito.doReturn(null).when(DataMapper).selectOne(Mockito.any(Wrapper.class));
commonManager.getDataByDate(LocalDateTime.now());
Mockito.doReturn(null).when(DataMapper).selectOne(Mockito.any(Wrapper.class));
Mockito.doThrow(new Exception("namederror")).when(DataMapper).selectOne(any());//抛出异常写法
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
上面这个maven里就有mockito,不用另外依赖