JUnit测试用例不是控制器中的检测方法

问题描述 投票:1回答:2

弹簧靴新手。

控制器中的API看起来像,

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

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

}

测试用例看起来像,

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

}

}

现在,在运行测试用例(命令1)之后,我得到了以下内容

“java.lang.AssertionError:预期状态:<200>但是:<404>”

但“命令2”按预期成功。

我的问题是,

RestController前缀路径+控制器前缀路径=整个路径。

对于调用API,我们必须遵循以上格式,但为什么如果遵循相同的东西,Junit会失败?

有人可以放弃一些输入吗?

java spring-boot junit testcase spring-boot-test
2个回答
2
投票
@RestController
@RequestMapping("/path1/path2")
public class SomeController
{

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

}

问题不在于您的测试类。问题是requestMapping的错误用法。


2
投票

在您的情况下,/path1/path2是控制器bean的名称。要为控制器内的所有方法添加通用前缀路径,您可以添加

@RequestMapping("/path1/path2")

在你的控制器上。

© www.soinside.com 2019 - 2024. All rights reserved.