开发测试代码可以使用 given-when-then 模式
添加依赖
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
</dependencies>
编写单元自测
@RunWith(MocktioJUnitRunner.class)
public class PolicyKeywordControllerTest{
@Mock
BizKeywordBizService bizKeywordBizService;
@InjectMocks
@Resource
PolicyKeywordController policyKeywordController;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test (junit)
public void addTest(){
PolicyKeywordFile policyKeywordFile = new PolicyKeywordFile();
when(bizKeywordBizService.addKeywordPolicy(PolicyKeywordFile)).thenReturn(1);
BaseResult baseResult = policyKeywordController.add(policyKeywordFile);
System.out.println(JSON.toJsonString(baseResult));
}
}
其他:
doNothing()
when(bizKeywordBizService.addKeywordPolicy(PolicyKeywordFile)).thenThrow(new RuntimeException("运行时异常"));