import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
maven中添加
<!-- mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<!-- junit 4 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
2.要调用的service用@InjectMocks注解,service里面用@Mock注解
@InjectMocks
@Autowired
private TestService testService;
@Mock
private TestMapper testMapper;
3.用@Before初始化mock
@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
}
4.模拟数据
when(testMapper.getTestList()).thenReturn(list1);
List<TestInfo> list = testService.getTestList();
assertEquals("bname", list.get(0).getTest_name());
转载于:https://blog.51cto.com/2302863/1655612