본문 바로가기

카테고리 없음

Mock Object만드는 방법

728x90

 

given을 쓰는 경우

 

@ExtendWith(MockitoExtension.class)
class MockTest {

	@Mock
	private RecordingService recordingService;

	@Test
	@DisplayName("given일때 어떤 object를 리턴할지 정하기")
	void givenTest(){
		given(recordingService.get(0l)).willReturn(Optional.of(new Recording(0l, "mock recording object")));
		Optional<Recording> recording = recordingService.get(0l);
		Assertions.assertEquals("mock recording object", recording.get().getTitle());
	}

}

 

doReturn을 쓰는 경우

아래 코드는 recordingService.list() 를 호출하면 recordings()의 리턴값을 리턴해준다는 뜻 입니다.

private List<Recording> recordings(){
    List<Recordings> recordings = new ArrayList<>();
    recordings.add(new Recording(0l, "first recording"));
    recordings.add(new Recording(1l, "second recording"));
    recordings.add(new Recording(2l, "third recording"));
}


@Test
void controllerTest(){
    doReturn(recordings()).when(recordingService).list();
    List<Recording> recordings = recordingService.list();
    Assertions.assertEquals("first recording", recordings.get(0).getTitle());
}

 

ControllerTest

@ExtendWith(MokitoExtension.class)
class RecordingServiceMockTest {

    @Mock
    private RecordingService recordingService; // Mock오브젝트 생성

    @InjectMocks
    private RecordingController recordingController; // @Mock어노테이션 붙은 오브젝트를 넣어줍니다

    private MockMvc mockMvc;

    @BeforeEach
    public void init() {
    	mockMvc = MockMvcBuilders.standaloneSetup(recordingController).build();
    }

    private List<Recording> recordings() {
        List<Recording> recordings = new ArrayList<>();
        recordings.add(new Recording(0l, "first recording"));
        recordings.add(new Recording(1l, "second recording"));
        recordings.add(new Recording(2l, "third recording"));
        return recordings;
    }

    @Test
    @DisplayName("controller test")
    void controllerTest() throws Exception {
    	doReturn(recordings()).when(recordingService).list();

        ResultActions resultActions = mockMvc.perform(
            MockMvcRequestBuilders.get("/api/v1/recording1/list")
        );
        MvcResult mvcResult = resultActions.andExpect(status().isOk()).andReturn();
        Assertions.assertEquals("[{\"id\":0", mvcResult.getResponse().getContentAsString().substring(0, 8));
    }
}

 

728x90
블로그 주인장입니다. 원하시는 정보는 얻으셨나요? 이 포스트에서 추가로 필요한 정보가 있으시면 여기에 남겨주세요.