1、引入 jar
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-test</artifactId> 4 <scope>test</scope> 5 </dependency>
2、被测试的类
1 @Service 2 @CustomLog 3 @Transactional(rollbackFor = Exception.class) 4 public class CasMonitorTaskServiceTx { 5 6 @Autowired 7 private WoMonitorTaskMapper woMonitorTaskMapper; 8 @Autowired 9 private WoMonitorRecordMapper woMonitorRecordMapper; 10 @Autowired 11 private SmsSendLogMapper smsSendLogMapper; 12 @Autowired 13 private SmsRecordClient smsRecordClient; 14 15 16 17 public void insertRecordAndSendSms() throws SchedulerException { 18 19 } 20 }
3、单元测试类
1 @ContextConfiguration(locations = {"classpath:test-service.xml", "classpath*:spring/root/public-*.xml"}) 2 @RunWith(SpringJUnit4ClassRunner.class) 3 @Transactional 4 public class CasMonitorTaskServiceTxTest { 5 7 @Autowired 8 private CasMonitorTaskServiceTx casMonitorTaskServiceTx; 9 10 11 @MockBean 12 private SmsRecordClient client; 13 14 @Test 15 public void insertRecordAndSendSms() throws Exception { 16 SmsRecordApi.SendRes res = new SmsRecordApi.SendRes(); 17 res.setMessage(Message.builder().ok(SmsRecordApi.SendRes.SendRes_Message.class)); 18 Mockito.doReturn(res).when(client).send(any()); 19 20 Long recordId = casMonitorTaskServiceTx.insertRecordAndSendSms(); 21 System.out.println(recordId); 22 } 23 24 25 }
说明:
CasMonitorTaskServiceTx类中除 SmsRecordClient之外的 bean 继续使用 spring容器进行加载 只需要mock feign 接口 SmsRecordClient,故在 test类中 mock SmsRecordClient类+注解 @MockBean
原创文章,作者:745907710,如若转载,请注明出处:https://blog.ytso.com/277630.html