如何在junit Mock测试中修复我的null ResponseEntity响应

时间:2018-06-07 14:32:43

标签: java spring-boot junit mockito resttemplate

我正在尝试使用另一个应用程序中的rest服务控制器中的响应实体来测试RestTemplate交换。我的Junit测试将返回null ResponseEntity。我尝试了几种没有运气的方法。首先尝试使用mockito来模拟响应方法(当...时)。第二次尝试使用Exchange匹配器。我也尝试将两者混合起来,没有运气。任何帮助都会很棒。这是我正在创建的Controller响应:

ResponseEntity<RestResult<List<SiteMessage>>> response = rest.exchange(getAllMessagesUrl, HttpMethod.GET,
    HttpEntity.EMPTY, new ParameterizedTypeReference<RestResult<List<SiteMessage>>>() {
});

这是我的Junit测试:

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class MessageControllerTests {

    @InjectMocks
    MessageController messageController;

    @Mock
    RestTemplate restTemplate;

    @Mock
    SiteMessageService serviceMock;

    @Mock
    ResponseEntity<RestResult<List<SiteMessage>>> response;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(messageController).build();
    }

    @Test
    public void testListPage() throws Exception {

        RestResult<List<SiteMessage>> result = new RestResult<>();

        result.setMessage("success");

        SiteMessage message1 = new SiteMessage();
        SiteMessage message2 = new SiteMessage();

        message1.setId("ldsf030j2ldjs");

        message2.setId("ldsf0432234s");


        List<SiteMessage> messageList = new ArrayList<>();
        messageList.add(message1);
        messageList.add(message2);

        result.setResults(messageList);

        when(response.getBody()).thenReturn(result);

        when(response.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND);

        when(restTemplate.exchange(
            Matchers.any(URI.class),
            Matchers.eq(HttpMethod.GET),
            Matchers.any(),
            Matchers.<ParameterizedTypeReference<RestResult<List<SiteMessage>>>>any())
        ).thenReturn(response);

        mockMvc.perform(get("/message/list")).andExpect(status().isOk()).andExpect(view().name("message/list"));
    }

}

我正在尝试使用包含RestResult对象的正文返回一个响应,该对象包含一个消息列表和一条消息

0 个答案:

没有答案