简述
目录
步骤
pom.xml修改
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
MyMockController.java
package com.ydfind.start.controller.test;
import com.ydfind.start.service.test.MyMockService;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* mock测试controller类
* @author ydfind
* @date 2020.1.17
*/
@RestController
@RequestMapping("/mock")
public class MyMockController {
@Autowired
MyMockService myMockService;
@Autowired
MyMockService myMockService1;
@GetMapping("/name")
@ApiImplicitParam(value = "获取名称")
public String getName(String id) {
return myMockService.getName(id);
}
@GetMapping("/name1")
@ApiImplicitParam(value = "获取名称")
public String getName1(String id) {
return myMockService1.getName(id);
}
}
service
package com.ydfind.start.service.test;
public interface MyMockService {
String getName(String id);
}
package com.ydfind.start.service.test.impl;
import com.ydfind.start.service.test.MyMockService;
import org.springframework.stereotype.Service;
@Service
public class MyMockServiceImpl implements MyMockService {
@Override
public String getName(String id) {
System.out.println(id + ": [" + id + "]");
return id + ": [" + id + "]";
}
}
test
package com.ydfind.start;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = MainApplication.class)
@RunWith(SpringRunner.class)
public abstract class BaseTest {
}
package com.ydfind.start.controller.test;
import com.ydfind.start.BaseTest;
import com.ydfind.start.service.test.MyMockService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
public class MyMockControllerTest extends BaseTest {
@Autowired
MyMockController myMockController;
@MockBean
MyMockService myMockService;
@Before
public void init() {
Mockito.doReturn("default_name").when(myMockService).getName(Mockito.anyString());
}
@Test
public void testGetName() {
Assert.assertEquals(myMockController.getName("1"), "default_name");
}
@Test
public void testGetName1() {
Assert.assertEquals(myMockController.getName1("1"), "default_name");
}
}
测试
因为对service进行了mock,所有service里面的代码是不会执行的。测试用例都会通过
备注
更多mockito请看:https://blog.csdn.net/sndayYU/article/details/103887552
测试相关请看:https://blog.csdn.net/sndayYU/article/details/103863847