如果我在spring工具包中创建一个标准的Spring项目,那就太棒了!
我访问localhost:8080 /问候并得到我的hello world响应.
如果我将这2个文件复制到我的源代码树中的另一个包中,然后访问localhost:8080/greeting我得到一个:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Oct 17 18:15:45 BST 2014
There was an unexpected error (type=Not Found, status=404).
Run Code Online (Sandbox Code Playgroud)
将3个类移动到相同的默认包中可以解决问题,但是从源树组织的角度来看,这不是我想要做的.
我希望这是由于一些自动配置所以请有人告诉我我必须做什么才能让我的项目支持多个包作为控制器和对象.
我正在尝试使用MockMvcBuilders.standaloneSetup方法为spring mvc rest控制器创建一个非常基本的单元测试.我一直收到404错误.下面我列出我的测试应用程序上下文,我的测试类,我的控制器和完整的堆栈跟踪.任何指导表示赞赏.
@Configuration
public class TestContext
{
@Bean
public Service service()
{
return mock(Service.class);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestContext.class})
@WebAppConfiguration
public class TestUsingWebAppContextSetUp
{
private MockMvc mockMvc;
@Autowired
private Service service;
@Before
public void setUp()
{
mockMvc = MockMvcBuilders.standaloneSetup(MyController.class)
.build();
}
@Test
public void test() throws Exception
{
mockMvc.perform(get("/search?phoneNumber=5551112222"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE));
}
}
public class MyController
{
@Autowired
private Service service;
@RequestMapping("/search")
public List<SearchResult> search(@RequestParam(value="phoneNumber") String phoneNumber)
{
System.out.println("search called");
Search search = new Search();
search.setPhoneNumber(phoneNumber);
return service.search(search);
}
} …Run Code Online (Sandbox Code Playgroud) @ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex, WebRequest request) {
StringBuilder messageBuilder = new StringBuilder("Validation failed for: ");
ex.getConstraintViolations()
.stream()
.forEach(v -> messageBuilder
.append("property: [" + v.getPropertyPath() + "], value: [" + v.getInvalidValue() + "], constraint: [" + v.getMessage() + "]"));
return new ResponseEntity<>(responseBuilder
.createErrorResponse(INVALID_PARAMETER,
messageBuilder.toString()), getHeaders(), BAD_REQUEST);
}
Run Code Online (Sandbox Code Playgroud)
我想测试这个@ControllerAdvice方法
spring ×2
spring-boot ×2
spring-mvc ×2
java ×1
java-8 ×1
junit ×1
mockito ×1
rest ×1
spring-test ×1