springboot整合Mockito

参考链接啊杰

流程

1.添加依赖



		
		
			org.mockito
			
			mockito-core
			
			2.7.19
			
			test
			
		


或者在文件中

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;

在类上添加注解。例如
(RunWith()是junit4的写法,junit5为ExtendWith())

@RunWith(MockitoJUnitRunner.class)
public class EmpServiceTest {
   } 

使用mockito.mock来mock需要mock的对象,从而获取一个新的对象,在service使用set方法注入该对象,不然无法调用mock的方法,

@Service
public class EmpService {
	    @Autowired
	    private EmpRepository empRepository;
	    
	    @Autowired
	    private EmpSortRepository empSortRepository;
	    
		public void setEmpRepository(EmpRepository empRepository){
		       this.empRepository  = empRepository;
		   }
   }
@Test
    public void test03(){
        EmpRepository empRepository = Mockito.mock(EmpRepository.class);
        empService.setEmpRepository(empRepository);
        Mockito.when(empRepository.countAllByEmpId()).thenReturn(3);
        int result = empService.countAll();
        System.out.println(result);
        /*Assert.assertEquals(3,result);*/
        Mockito.verify(empRepository).countAllByEmpId();
    }

你可能感兴趣的:(springboot整合Mockito)