SpringMVC 프로젝트가 있습니다. 테스트하려는 FooController의 메서드는 다음과 같습니다.
@GetMapping("/view/{fooId}")
public String view(@PathVariable String fooId, Model model) throws FooNotFoundException, JsonProcessingException {
Foo foo = fooService.getFoo(fooId);
model.addAttribute("fooId", foo.getId());
model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo));
return "foo/view";
}
내가 작성한 테스트는 다음과 같습니다.
public class FooControllerTest {
@Mock
private Foo mockFoo;
@Mock
private FooService mockFooService;
@InjectMocks
private FooController controller;
private MockMvc mockMvc;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void testView() throws Exception {
String fooId = "fooId";
when(mockFooService.getFoo(fooId)).thenReturn(mockFoo);
when(mockFoo.getId()).thenReturn(fooId);
mockMvc.perform(get("/foo/view/" + fooId))
.andExpect(status().isOk())
.andExpect(model().attribute("fooId", fooId))
.andExpect(model().attributeExists("foo"))
.andExpect(forwardedUrl("foo/view"));
}
}
이 테스트는 java.lang.AssertionError: No ModelAndView found
. 내가 테스트를 디버깅 할 때, 나는 나의이 때 잘못보고 mockFoo
주어집니다 new ObjectMapper.writeValueAsString()
. 그래서 모의 객체는 직렬화 할 수 없다고 생각합니다. 이 문제를 해결하려면 어떻게해야합니까? 테스트를 통과하려면 어떻게해야합니까?
model.addAttribute("foo", new ObjectMapper().writeValueAsString(foo));
FooController 의 줄 에 주석을 달았 는데, 이런 방식으로 테스트가 작동했습니다 (하지만 내가 원하는 방식은 아닙니다)! 그래서 이제 나는 이것이 잘못된 곳임을 압니다..andExpect(model().attributeExists("foo"))
FooControllerTest 의 줄 에 주석을 달았 지만 여전히 위의 AssertionError를 생성했습니다.동료가 다음을 제안했습니다.를 사용하는 대신 mockFoo
새 Foo 객체를 만들어 다음과 같이 사용했습니다.
@Test
public void testView() throws Exception {
String fooId = "fooId";
Foo foo = new Foo(fooId);
when(mockFooService.getFoo(fooId)).thenReturn(foo);
mockMvc.perform(get("/foo/view/" + fooId))
.andExpect(status().isOk())
.andExpect(model().attribute("fooId", fooId))
.andExpect(model().attributeExists("foo"))
.andExpect(forwardedUrl("foo/view"));
}
작동합니다. 나는 항상 당신이 테스트하지 않는 모든 객체를 모의해야한다고 생각했습니다 (따라서 컨트롤러에서는 컨트롤러 자체를 제외한 모든 것을 모의합니다). 그러나 Foo
단순한 POJO 이기 때문에 조롱 할 필요가 없습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다