【问题标题】:Unit testing spring boot controller with Mockito使用 Mockito 对 Spring Boot 控制器进行单元测试
【发布时间】:2019-07-07 16:34:51
【问题描述】:

我有以下控制器:

@RestController
@RequestMapping("cats")
public class CatController {
    private IDatabaseCatDao databaseCatService;
    private DataValidator catDataValidator;

    public CatController(IDatabaseCatDao databaseCatService, DataValidator catDataValidator) {
        this.databaseCatService = databaseCatService;
        this.catDataValidator = catDataValidator;
    }

    @PostMapping
    public ResponseEntity addCat(@RequestBody Cat cat) {
        catDataValidator.validateCatAdding(cat, cats);
        databaseCatService.addCat(cat);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(cat.getName()).toUri();
        return ResponseEntity.created(location).build();
    }
}    

catDataValidator - 检查数据是否正确
databaseCatService - 插入数据库 + 本地缓存

我需要使用 jUnitMockito 对其进行测试。

我的测试课如下:

@RunWith(SpringRunner.class)
@WebMvcTest(value = CatController.class, secure = false)
public class CatControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private IDatabaseCatDao databaseCatService;

    private String catExampleJson = "..some json file..";

   public void addCat() throws Exception {
        Mockito.doNothing().when(databaseCatService).addCat(Mockito.any(Cat.class));
        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post("/cats")
                .accept(MediaType.APPLICATION_JSON).content(catExampleJson)
                .contentType(MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = result.getResponse();
        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
    }
}

Mockito.doNothing() 因为服务 addCat() 是 void 方法。
验证我最好单独测试
Cats map em> 我这里不用

java.lang.Exception: 没有可运行的方法

at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:137)
    at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:36)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

我有以下测试依赖项

spring-boot-starter-test

【问题讨论】:

    标签: java testing junit mocking mockito


    【解决方案1】:

    您需要使用 @Test 注释您的测试方法,以便 SpringRunner 能够找到它。即:

    @Test
    public void addCat() throws Exception {
    

    【讨论】:

    • 哦,我的上帝..它是不可动摇的,ty
    • 你能告诉我关于 Mockito.doNothing(),当我尝试调用 void method(),当我在这个方法中有一些异常时它不会工作,对吧?
    • Mockito.doNothing() 在您使用Spy 而不是Mock 时最有用,因为您可以防止在真实对象上执行不需要的方法。
    • 您可以,但不能使用Mock。您必须使用Spy。有一个 @SpyBean 注释。但是除非您别无选择,否则强烈不鼓励使用间谍。更好的方法是创建一个新的测试类来专门测试您感兴趣的任何类。
    猜你喜欢
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多