Status Expected:<200> But Was:<404> in Spring Test

Status expected:<200> but was:<404> in spring test while testing my spring boot test cases

The HTTP 400 response indicates a bad request. Your HTTP GET endpoint expects an int while you're sending a String as the path variable.

So accountNumber must be a real number like 123:

MvcResult result = mockMvc
.perform(get("/account/123")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andReturn();

Spring Boot JUnit tests fail with Status expected:<200> but was:<404>

The @ContextConfiguration annotation is used for a different purpose:

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.

Using Spring Boot and @WebMvcTest there's no need to manually specify how to load the context. That's done for you in the background.

If you'd use this annotation, you'd specify your main Spring Boot class here (your entry-point class with the @SpringBootApplication annotation).

From what I can see in your test and your question is that you want to provide an actual bean for the TravelOutputDtoMapper, but mock the TravelService.

In this case, you can use @TestConfiguration to add further beans to your sliced Spring TestContext:

// @ExtendWith(SpringExtension.class) can be removed. This extension is already registered with @WebMvcTest
@WebMvcTest(controllers = TravelController.class)
class TravelControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private TravelService travelService;

@Autowired
private TravelOutputDtoMapper travelOutputDtoMapper;


@TestConfiguration
static class TestConfig {

@Bean
public TravelOutputDtoMapper travelOutputDtoMapper() {
return new TravelOutputDtoMapper(); // I assume your mapper has no collaborators
}
}

// ... your MockMvc tests
}

java.lang.AssertionError: Status expected:<200> but was:<404> Spring Boot Page Not found

You have conflicting profiles. Your controller is annotated with @Profile("!test") while your test is executing with @ActiveProfiles("test").

Spring boot controller test returns 200 when expected is 404

Your controller does not have the logic that you expect to test. Here is how your controller should be implemented to behave the way you want it to

@RestController
public class CustomerController {

@Autowired
private CustomerService customerService;

@GetMapping(path = "/customers/{id}")
public ResponseEntity<Customer> findCustomerById(@PathVariable("id") Long id){
Optional<Customer> optCust = customerService.findById(id);
if (optCust.isPresent()){
return ResponseEntity.ok(optCust.get());
} else {
return ResponseEntity.notFound().build()
}
}
}


Related Topics



Leave a reply



Submit