스프링


mockito

->테스트를 위한 객체 생성 라이브러리

 

https://mvnrepository.com/artifact/org.mockito/mockito-core

 

http://site.mockito.org/

 

 

mockito 사용법(mockito usage)

 

 

class RedirectControllerTest

package com.java.web;

import static org.hamcrest.CoreMatchers.any;
import static org.junit.Assert.*;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import javax.inject.Inject;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mock.*;
import org.mockito.*;

import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.setup.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.springframework.web.context.WebApplicationContext;

import com.java.dao.users.UserDao;
import com.java.dto.User;

import org.mockito.junit.*;

@RunWith(MockitoJUnitRunner.class)
public class RedirectControllerTest {

	@Mock
	private UserDao userDao;

	@InjectMocks
	private UserController userController;

	private MockMvc mockMvc;

	@Before
	public void setUp() throws Exception {
		this.mockMvc = standaloneSetup(userController).build();
	}

	@Test
	public void crateWhenValid() throws Exception {
		this.mockMvc
				.perform(post("/users").param("userId", "javagigsi").param("password", "passwords")
						.param("name", "자바지기dd").param("email", "test@gmail.com"))
				.andDo(print())
				// .andExpect(status().isMovedTemporarily())
				.andExpect(redirectedUrl("/"));
	}

	@Test
	public void crateWhenInvalid() throws Exception {
		this.mockMvc
				.perform(post("/users").param("userId", "javagigsi").param("password", "passwords")
						.param("name", "자바지기d").param("email", "test"))
				.andDo(print()).andExpect(status().isOk()).andExpect(forwardedUrl("users/form"));
	}

	@Test
	public void example() {
		User p = mock(User.class);
		assertTrue(p != null);
	}

	// 만약 예외를 던지고 싶으면 어떻게 할까요? 이럴때는 doThrow() 메소드를 활용합시다.
	@Test(expected = IllegalArgumentException.class)
	public void example2() {
		User p = mock(User.class);
		doThrow(new IllegalArgumentException()).when(p).setName("JDM");
		String name = "JDM";
		p.setName(name);
	}

	// verifiy()는 해당 구문이 호출 되었는지를 체크합니다.
	// 단순한 호출뿐만 아니라 횟수나 타임아웃 시간까지 지정해서 체크해 볼 수 있습니다.
	@Test
	public void example3() {
		User p = mock(User.class);
		String name = "JDM";
		p.setName(name);
		// n번 호출했는지 체크
		verify(p, times(1)).setName(name); // success
		// 호출 안했는지 체크
		verify(p, never()).getName(); // success
		verify(p, never()).setName("ETC"); // success
		verify(p, never()).setName("JDM"); // fail
		// 최소한 1번 이상 호출했는지 체크
		verify(p, atLeastOnce()).setName(name); // success
		// 2번 이하 호출 했는지 체크
		verify(p, atMost(2)).setName(name); // success
		// 2번 이상 호출 했는지 체크
		verify(p, atLeast(2)).setName(name); // fail
		// 지정된 시간(millis)안으로 메소드를 호출 했는지 체크
		verify(p, timeout(100)).setName(name); // success
		// 지정된 시간(millis)안으로 1번 이상 메소드를 호출 했는지 체크
		verify(p, timeout(100).atLeast(1)).setName(name); // success
	}
	
	
}

 

 

INFO : org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 3 ms

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /users
       Parameters = {userId=[javagigsi], password=[passwords], name=[자바지기dd], email=[test@gmail.com]}
          Headers = {}

Handler:
             Type = com.java.web.UserController
           Method = public java.lang.String com.java.web.UserController.create(com.java.dto.User,org.springframework.validation.BindingResult)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = users/form
             View = null
        Attribute = user
            value = User [userId=javagigsi, password=passwords, name=자바지기dd, email=test@gmail.com]
           errors = [Field error in object 'user' on field 'userId': rejected value [javagigsi]; codes [Min.user.userId,Min.userId,Min.java.lang.String,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.userId,userId]; arguments []; default message [userId],4]; default message [must be greater than or equal to 4], Field error in object 'user' on field 'userId': rejected value [javagigsi]; codes [Max.user.userId,Max.userId,Max.java.lang.String,Max]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.userId,userId]; arguments []; default message [userId],12]; default message [must be less than or equal to 12]]

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = users/form
   Redirected URL = null
          Cookies = []
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users/form]}" onto public java.lang.String com.java.web.UserController.form(org.springframework.ui.Model)
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users],methods=[POST]}" onto public java.lang.String com.java.web.UserController.create(com.java.dto.User,org.springframework.validation.BindingResult)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@46ab18da
INFO : org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 0 ms
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users/form]}" onto public java.lang.String com.java.web.UserController.form(org.springframework.ui.Model)
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users],methods=[POST]}" onto public java.lang.String com.java.web.UserController.create(com.java.dto.User,org.springframework.validation.BindingResult)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@327120c8
INFO : org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 0 ms

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /users
       Parameters = {userId=[javagigsi], password=[passwords], name=[자바지기d], email=[test]}
          Headers = {}

Handler:
             Type = com.java.web.UserController
           Method = public java.lang.String com.java.web.UserController.create(com.java.dto.User,org.springframework.validation.BindingResult)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = users/form
             View = null
        Attribute = user
            value = User [userId=javagigsi, password=passwords, name=자바지기d, email=test]
           errors = [Field error in object 'user' on field 'email': rejected value [test]; codes [Email.user.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@3a7b503d,.*]; default message [not a well-formed email address], Field error in object 'user' on field 'userId': rejected value [javagigsi]; codes [Max.user.userId,Max.userId,Max.java.lang.String,Max]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.userId,userId]; arguments []; default message [userId],12]; default message [must be less than or equal to 12], Field error in object 'user' on field 'userId': rejected value [javagigsi]; codes [Min.user.userId,Min.userId,Min.java.lang.String,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.userId,userId]; arguments []; default message [userId],4]; default message [must be greater than or equal to 4]]

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = users/form
   Redirected URL = null
          Cookies = []
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users/form]}" onto public java.lang.String com.java.web.UserController.form(org.springframework.ui.Model)
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users],methods=[POST]}" onto public java.lang.String com.java.web.UserController.create(com.java.dto.User,org.springframework.validation.BindingResult)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@4d0402b
INFO : org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 0 ms
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users/form]}" onto public java.lang.String com.java.web.UserController.form(org.springframework.ui.Model)
INFO : org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping - Mapped "{[/users],methods=[POST]}" onto public java.lang.String com.java.web.UserController.create(com.java.dto.User,org.springframework.validation.BindingResult)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.test.web.servlet.setup.StubWebApplicationContext@106faf11
INFO : org.springframework.mock.web.MockServletContext - Initializing Spring FrameworkServlet ''
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 0 ms

 

 

 

 

 

spring

 

about author

PHRASE

Level 60  머나먼나라

교태가 참된 사랑에 의해 무너지듯이 질투는 참된 우정에 의해 무너진다. -라 로슈프코

댓글 ( 4)

댓글 남기기

작성