Search code examples
javaspring-bootjunittestcasespring-boot-test

JUnit Test Case is not detecting method in controller


New to spring boot.

API in controller looks like,

@RestController("/path1/path2")
public class SomeController
{

@GetMapping("/path3/path4")
public String doSomething()
{
//code goes here
}

}

Test case looks like,

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = 
xxx.class)
@AutoConfigureMockMvc(secure = false)
public class AuthServiceTestCase
{

@Autowired
private MockMvc mock;

@Test
public void testDoSomething()
{

//Command 1
mock.perform(get("/path1/path2/path3/path4")).andExpect(status().isOK()); 

//Command 2
 mock.perform(get("/path3/path4")).andExpect(status().isOK()); 

}

}

Now, after running test case (Command 1), I have got the following

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

But the "Command 2" succeeded as expected.

My question is,

RestController Prefix Path + Controller Prefix Path = Entire Path.

For invoking an API, we have to follow above format, but why Junit fails if followed same stuff?

Could some one drop some inputs here?


Solution

  • @RestController
    @RequestMapping("/path1/path2")
    public class SomeController
    {
    
    @GetMapping("/path3/path4")
    public String doSomething()
    {
    //code goes here
    }
    
    }
    

    The problem is not your test class. Problem is the wrong usage of requestMapping.