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

标签 java spring spring-boot junit5 spring-restdocs

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

休息 Controller

@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?

最佳答案

嗨,在我的例子中,我需要 Controller 的 @MockBean 和所有 Autowiring 的服务;)

关于java.lang.AssertionError : Status expected:<200> but was:<404> in Junit test 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53904887/

相关文章:

java - 需要帮助让 JRadioButton 将值返回到 JTextField

java - 流式传输用户上传的视频文件

java - Liferay Spring 集成

spring - Tomcat...网络应用启动顺序

spring-boot - 带有bootRun且未优化启动的Spring Boot应用程序(kotlin,gradle)中的性能低下= false

java - 从 CLASSPATH 中目录的子目录获取文件路径

java - setTextColor() - 逻辑错误

java - 未找到 Jersey 类...但它就在那里

java - 轴突框架 : Change processing order between @EventHandler and @EventSourcingHandler

Spring Security 具有不同用户详细信息的多个 HTTPSecurity 服务在 Spring Boot 中不起作用