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

11,818

hi in my case i needed @MockBean of controller and all services that is was autowireing ;)

Share:
11,818
Peter Penzov
Author by

Peter Penzov

Updated on June 04, 2022

Comments

  • Peter Penzov
    Peter Penzov almost 2 years

    I want to create JUnit test for Rest api and generate api doc. I want to test this code:

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

    Repository interface

    public interface PaymentTransactionRepository extends CrudRepository<PaymentTransactions, Integer>, JpaSpecificationExecutor<PaymentTransactions> {
    
        Optional<PaymentTransactions> findById(Integer id);
    }
    

    I tried to implement this JUnit5 test with mockito:

    @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`"))));
        }
    }
    

    I get error:

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

    What his the proper way to to make GET request to the above code? Probably I need to add response OK when message is send back?

  • Peter Penzov
    Peter Penzov over 5 years
    I get java.lang.AssertionError: Status expected:<200> but was:<404> at this line .andExpect(status().isOk()) Any idea why?
  • Pradip Karki
    Pradip Karki over 5 years
    Can you please try add below line before this.mockMvc.perform given(target.findById(anyInt())).willReturn(Optional.of(new PaymentTransactions(1))); and see if this works?
  • Pradip Karki
    Pradip Karki over 5 years
    @PeterPenzov sure, please try it.
  • Peter Penzov
    Peter Penzov over 5 years
    I tried it but I get again error 404. Any idea how to debug it?
  • Pradip Karki
    Pradip Karki over 5 years
    yea, you can definitely. I updated the answer, please look at it.
  • Peter Penzov
    Peter Penzov over 5 years
    Do you know what maven dependencies I have to import for andReturn();?
  • Peter Penzov
    Peter Penzov over 5 years
    By the wya I use JUnit 5 looks like your code is for JUnit 4?
  • Pradip Karki
    Pradip Karki over 5 years
    you can import import org.springframework.test.web.servlet.MvcResult; you can get the library mvnrepository.com/artifact/org.springframework.boot/….
  • Peter Penzov
    Peter Penzov over 5 years
    With cast I managed to implement it but I get compilation error. This code is probably for JUnit 4?
  • Pradip Karki
    Pradip Karki over 5 years
    Yea, It’s in jUnit 4, but idea is you can printout, debug results using MvcResult and other helpful methods.
  • Pradip Karki
    Pradip Karki over 5 years
    one example I found using jUnit 5 is: stackoverflow.com/questions/48727758/…, but it should be same. Can you post the compilation error message too? and your url should be like /transactions/1
  • Peter Penzov
    Peter Penzov over 5 years
    I get NPE at this line MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/transactions/{i‌​d}", 1))
  • pramesh
    pramesh over 5 years
    can you replace by this code in your setup, i think PaymentTransactionsController is not injected in your test so you are getting NPE @Before public void setUp() { MockitoAnnotations.initMocks(this); mvc = MockMvcBuilders.standaloneSetup(new PaymentTransactionRepository()).build(); }
  • pramesh
    pramesh over 5 years
    i have small demo for unit test in my git repo... it can help you.. github.com/prameshbhattarai/spring-boot-demo
  • Peter Penzov
    Peter Penzov over 5 years
    I get again NPE at the same line.
  • pramesh
    pramesh over 5 years
    can you provide me the stack trace for your exception... also did you check my repo..
  • Peter Penzov
    Peter Penzov over 5 years
    Here is the output: pastebin.com/06b7XsFH I will test your code example today.
  • AngularPlayer
    AngularPlayer about 2 years
    This worked to me, why ???