测试 MockBean 为空

dar*_*gui 8 testing spring mockito spring-boot

我有这个类的定义

@RestController
public class ReservationController {
    @Autowired
    private Reservation reservation;

    @RequestMapping(value = "/reservation", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
    @ResponseBody
    public Reservation getReservation() {

        return reservation;
    }
}
Run Code Online (Sandbox Code Playgroud)

其中 Reservation 是一个简单的 Pojo

public class Reservation {
    private long id;
    private String reservationName;

    public Reservation() {
        super();
        this.id = 333;
        this.reservationName = "prova123";
    }

    public Reservation(long id, String reservationName) {
        super();
        this.id = id;
        this.reservationName = reservationName;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getReservationName() {
        return reservationName;
    }

    public void setReservationName(String reservationName) {
        this.reservationName = reservationName;
    }

    @Override
    public String toString() {
        return "Reservation [id=" + id + ", reservationName=" + reservationName + "]";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试测试这门课时

@WebMvcTest
@RunWith(SpringRunner.class)
public class MvcTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean(name = "reservation")
    private Reservation reservation;

    @Test
    public void postReservation() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.post("/reservation"))
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是org.springframework.http.converter.HttpMessageConversionException:类型定义错误:[简单类型,类org.mockito.internal.debugging.LocationImpl];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidDefinitionException:找不到类 org.mockito.internal.debugging.LocationImpl 的序列化器,并且没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链: spring.boot.usingSpringBoot.entity.Reservation$MockitoMock$980801978["mockitoInterceptor"]->org.mockito.internal.creation.bytebuddy.MockMethodInterceptor["mockHandler"]->org.mockito.internal.handler.InitationNotifierHandler["invocalContainer "]->org.mockito.internal.stubbing.InvocableContainerImpl["invocalForStubbing"]->org.mockito.internal.invocal.InvocableMatcher["invocation"]->org.mockito.internal.inspiration.InterceptedInitation["location"] )

......

原因:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:没有找到类 org.mockito.internal.debugging.LocationImpl 的序列化器,并且没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链) : spring.boot.usingSpringBoot.entity.Reservation$MockitoMock$980801978["mockitoInterceptor"]->org.mockito.internal.creation.bytebuddy.MockMethodInterceptor["mockHandler"]->org.mockito.internal.handler.InitationNotifierHandler["invocalContainer "]->org.mockito.internal.stubbing.InvocableContainerImpl["invocalForStubbing"]->org.mockito.internal.invocal.InvocableMatcher["invocation"]->org.mockito.internal.inspiration.InterceptedInitation["location"] )

我怎样才能以正确的方式注入预订?

谢谢

Evg*_*rov 5

您收到错误是因为当您使用@MockBean(或@Mock在非 Spring 环境中)时您会得到一个 Mockito 模拟对象。该对象是您的对象的空代理。该代理具有与您的类相同的公共方法,并且默认情况下返回其返回类型的默认值(例如,对象为 null,int 为 1 等),或者对于 void 方法不执行任何操作。

Jackson 抱怨是因为它必须序列化这个没有字段的代理,而 Jackson 不知道该怎么办。

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:没有找到类 org.mockito.internal.debugging.LocationImpl 的序列化器,并且没有发现创建 BeanSerializer 的属性(为避免异常,请禁用 SerializationFeature.FAIL_ON_EMPTY_BEANS

一般来说,当您模拟要测试的某个类的依赖项时,您会模拟它在您测试的类中使用的公共方法。直接返回您的依赖项并不是一个好的现实用例 - 您不太可能需要编写这样的代码。

我猜你正在努力学习,所以让我提供一个改进的例子:

@RestController
public class ReservationController {
    @Autowired
    private ReservationService reservationService;     //my chnage here

    @RequestMapping(value = "/reservation", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST)
    @ResponseBody
    public Reservation getReservation() {

        return reservationService.getReservation();   //my chnage here
    }
}
Run Code Online (Sandbox Code Playgroud)

您通常不会直接注入值对象,而是拥有一个包含一些业务逻辑并返回某些内容的服务类 - 在我的示例中,ReservationService它有一个getReservation()返回类型和对象的方法Reservation

有了这个,在你的测试中你就可以模拟ReservationService.

@WebMvcTest
@RunWith(SpringRunner.class)
public class MvcTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean(name = "reservation")
    private ReservationService reservationService;    //my chnage here

    @Test
    public void postReservation() throws Exception {
        // You need that to specify what should your mock return when getReservation() is called. Without it you will get null
        when(reservationService.getReservation()).thenReturn(new Reservation()); //my chnage here

        mockMvc.perform(MockMvcRequestBuilders.post("/reservation"))
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }
}
Run Code Online (Sandbox Code Playgroud)