java.lang.AssertionError:预期状态:<200>,但在Junit测试中为:<404>

时间:2018-12-23 15:33:33

标签: java spring spring-boot junit5 spring-restdocs

我想为Rest api创建JUnit测试并生成api doc。我想测试这段代码:

其他控制器

@RestController
@RequestMapping("/transactions")
public class PaymentTransactionsController {

@Autowired
private PaymentTransactionRepository transactionRepository;

@GetMapping("{id}")
    public ResponseEntity<?> get(@PathVariable String id) {
        return transactionRepository
                .findById(Integer.parseInt(id))
                .map(mapper::toDTO)
                .map(ResponseEntity::ok)
                .orElseGet(() -> notFound().build());
    }
}

存储库界面

public interface PaymentTransactionRepository extends CrudRepository<PaymentTransactions, Integer>, JpaSpecificationExecutor<PaymentTransactions> {

    Optional<PaymentTransactions> findById(Integer id);
}

我尝试使用Mockito实现此JUnit5测试:

@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = PaymentTransactionsController.class)
@WebAppConfiguration
public class PaymentTransactionRepositoryIntegrationTest {
    .....
    private MockMvc mockMvc;

    @MockBean
    private PaymentTransactionRepository transactionRepository;

    @BeforeEach
    void setUp(WebApplicationContext webApplicationContext,
              RestDocumentationContextProvider restDocumentation) {

        PaymentTransactions obj = new PaymentTransactions(1);

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

        PaymentTransactionRepository processor = Mockito.mock(PaymentTransactionRepository.class);
        Mockito.when(processor.findById(Integer.parseInt("1"))).thenReturn(optional);       

        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
              .apply(documentationConfiguration(restDocumentation))
              .alwaysDo(document("{method-name}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
              .build();
    }

    @Test
    public void testNotNull() {
        assertNotNull(target);
    }

    @Test
    public void testFindByIdFound() {
        Optional<PaymentTransactions> res = target.findById(Integer.parseInt("1"));
//        assertTrue(res.isPresent());
    }

    @Test
    public void indexExample() throws Exception {
            this.mockMvc.perform(get("/transactions").param("id", "1"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/xml;charset=UTF-8"))
                .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`"))));
    }
}

我收到错误消息:

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

他对上述代码进行GET请求的正确方法是什么? 回信时可能需要添加响应OK吗?

4 个答案:

答案 0 :(得分:1)

嗨,在我的情况下,我需要控制器的@MockBean 和所有自动装配的服务;)

答案 1 :(得分:0)

这是一个路径变量,因此,请不要使用参数值,而应使用路径变量。

对于MvcResult导入,您可以导入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`"))));

答案 2 :(得分:0)

可以尝试一下吗。

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());
}
}

答案 3 :(得分:0)

代替@PostMapping和@GetMapping会导致相同的问题,而控制器中的@RequestMapping帮助