Mock簡單使用
原因:
如果要測試一個功能是否完善,但是某個方法又依賴別的接口,別的接口可能沒有開發完,此時如果使用正常的測試的話,那麼沒有開發完的接口可能會阻塞自測的流程
使用mock的優點
- 與寫死其他接口返回結果不同,Mock不需要修改原方法的代碼
不說廢話,直接開始
public interface CarService3 {
String addPetroleum();
}
package cn.withmes.spring.boot.mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Service
public class CarServiceImpl3 implements CarService3{
@Autowired
private PertoleumService pertoleumService;
@Override
public String addPetroleum(){
return "此次一共加油"+pertoleumService.addMl()+"ml";
};
}
public interface PertoleumService {
String addMl();
}
package cn.withmes.spring.boot.mockito;
import org.springframework.stereotype.Service;
@Service
public class PertoleumServiceImpl implements PertoleumService {
@Override
public String addMl() {
throw new RuntimeException("其他結果拋出異常!");
}
}
正常測試,結果拋出異常
package cn.withmes.spring.boot.mockito;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import static org.mockito.Mockito.when;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootMockitoApplicationTests2 {
@Autowired
private PertoleumService pertoleumService;
@Autowired
private CarService3 carService3;
@Test
public void mock1 () {
String s = carService3.addPetroleum();
System.out.println(s);
//java.lang.RuntimeException: 其他結果拋出異常!
}
}
使用mock,這樣達到了不修改代碼的情況下。對功能進行測試
package cn.withmes.spring.boot.mockito;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import static org.mockito.Mockito.when;
@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBootMockitoApplicationTests2 {
@Mock
@Autowired
private PertoleumService pertoleumService;
@InjectMocks
@Autowired
private CarServiceImpl3 carService3; //注意這裏使用的是Impl
@Before
public void before () {
MockitoAnnotations.initMocks(this);
}
@Test
public void mock2 () {
when(pertoleumService.addMl()).thenReturn("111");
String s = carService3.addPetroleum();
System.out.println(s);
//此次一共加油111ml
}
}