MockBean 未注入 MVC 控制器测试中

zak*_*zak 0 java spring-mvc mockito spring-test-mvc

我正在尝试与 Spring 应用程序上下文隔离来测试我的控制器。

这是我的控制器

@RestController
public class AddressesController {

    @Autowired
    service service;

    @GetMapping("/addresses/{id}")
    public Address getAddress( @PathVariable Integer id ) {
        return service.getAddressById(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的服务界面

public interface service {
    Address getAddressById(Integer id);
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试课

@ExtendWith(SpringExtension.class)
@WebMvcTest
public class AddressControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    service myService;

    @Test
    public void getAddressTest() throws Exception {
        Mockito.doReturn(new Address()).when(myService).getAddressById(1);
        mockMvc.perform(MockMvcRequestBuilders.get("/addresses/1"))
                .andExpect(status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的异常:

org.mockito.exceptions.misusing.NullInsteadOfMockException:传递给when()的参数为空!正确存根的示例: doThrow(new RuntimeException()).when(mock).someMethod(); 另外,如果你使用 @Mock 注解,不要错过 initMocks()

就像服务从未被创建一样。我该如何解决这个问题?

@RunWith(SpringRunner.class)我们可以通过使用代替来解决这个问题@ExtendWith(SpringExtension.class)。有人可以解释为什么它有效吗?通常第一个注释适用于 junit4,第二个注释适用于 junit5。

zak*_*zak 5

不幸的是,由于依赖问题,问题得到了解决。

我的 pom.xml 文件包含spring-boot-starter-test,如果我们检查包含此启动程序的内容,我们会发现它包含 junit4 作为依赖项,而不是 junit5。

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>compile</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的测试类中使用 Junit5 和 @ExtendWith(SpringExtension.class) 时,测试不幸地编译但给出了运行时错误。我通过从 Spring Boot 启动器中排除 junit4 解决了这个问题:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

我的 pom.xml 还应该包含 junit5 依赖项

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.3.2</version>
    <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)