1. 导入依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.19.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>2.0.0-beta.5</version>
<scope>test</scope></dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0-beta.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0-beta.5</version>
<scope>test</scope>
</dependency>
2. 环境准备
实体类 TestUtil
package com.test.util;
public class TestUtil {
public static String toLowercase(String param) {
if(param==null){
throw new IllegalArgumentException();
}
return param.toLowerCase();
}
public static String sayBye(String param) {
return "...";
}
}
实体类 TestController
package com.test.controller;
import com.test.service.TestService;
import com.test.util.TestUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
@RestController
@RequestMapping("test")
public class TestController {
@Value("${user}")
private String user;
@GetMapping("greet")
public String method1(String param) {
return user+":"+TestUtil.toLowercase(param);
}
@GetMapping("bye")
public String method2(String param) {
return TestUtil.sayBye(param);
}
}
3. 接口测试
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.test.util.ReflectionTestUtils;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestUtil.class)
public class TestControllerTest {
private static Logger log = LoggerFactory.getLogger(TestControllerTest.class);
@InjectMocks
private TestController testController;
@Mocks
private TestService testService;
@Before
public void setUp() {
PowerMockito.mockStatic(TestUtil.class);
}
@Test
public void method1(){
String user="yue"
ReflectionTestUtils.setField(TestController, "user", user);
String param="hello world";
when(TestUtil.toLowercase(param)).thenReturn(param);
when(TestUtil.Lowercase (null)).thenThrow(new IllegalArgumentException());
String result=testController.method1(param);
Assert.assertEquals(result,user":"+param);
}
@Test
public void method2(){
String param="hello world";
Mockito.doNothing().when(TestUtil).(sayBye);
String result=testController.method2(param);
Assert.assertEquals(result,...);
}
}