java.lang.AssertionError: Status expected:<200> but was:<404> in Junit test

北城以北 提交于 2019-12-06 06:04:16

It's a path variable, so instead of using param value, please use path variable.

For MvcResult import, you can import org.springframework.test.web.servlet

import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

...

given(target.findById(anyInt())).willReturn(Optional.of(new PaymentTransactions(1))).andReturn();

MvcResult result = this.mockMvc.perform(get("/transactions/1")
                .accept("application/xml;charset=UTF-8")).andReturn();

String content = result.getResponse().getContentAsString();

this.mockMvc.perform(get("/transactions/1")
            .accept("application/xml;charset=UTF-8"))
            .andExpect(status().isOk())
            .andDo(document("index-example", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), links(linkWithRel("crud").description("The CRUD resource")), responseFields(subsectionWithPath("_links").description("Links to other resources")),
                responseHeaders(headerWithName("Content-Type").description("The Content-Type of the payload, e.g. `application/hal+json`"))));

Can you try this..

public class PaymentTransactionsControllerTest {

private MockMvc mvc;

@InjectMocks
PaymentTransactionsController paymentTransactionsController;

@MockBean
private PaymentTransactionRepository processor;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders.standaloneSetup(paymentTransactionsController).build();
}

@Test
public void indexExample() throws Exception {

    PaymentTransactions obj = new PaymentTransactions(1);
    Optional<PaymentTransactions> optional = Optional.of(obj);  

    Mockito.when(processor.findById(Integer.parseInt("1"))).thenReturn(optional); 

    MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/transactions/{id}", 1))
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();

    Assert.assertNotNull(result.getResponse().getContentAsString());
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!