mockito、easymock、powermock使用(4)-Controller層試験

2704 ワード

目的
controller層テストコードを作成し、シミュレーションコードの実行結果
準備工作
mockito、easymock、powermock使用(2)-準備作業
テストコード
import com.suning.work.controller.MockController;
import com.suning.work.model.MockBean;
import com.suning.work.service.MockService;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RunWith(PowerMockRunner.class)
/**
 *     
 * previously initiated loading for a different type with name "javax/management/MBeanServer"
 * Failed to instantiate [ch.qos.logback.classic.LoggerContext]
 */
@PowerMockIgnore("javax.management.*")
public class MockControllerTest extends TestCase {

    /**
     *     
     */
    @InjectMocks
    MockController mockController;

    /**
     *     
     * Mock      InjectMocks   
     */
    @Mock
    MockService mockService;

    HttpServletRequest request;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
         /**
         *  mock request   
         */
        request = (HttpServletRequest) EasyMock.createMock(HttpServletRequest.class);
    }

    @Test
    public void test(){
        Mapmap=null;

        //    
        MockBean bean=new MockBean();
        bean.setCode("1001");
        bean.setCreateDate("2018-12-12 12:12:12");

        //      
        PowerMockito.when(mockService.update(bean)).thenReturn(true);
        map= mockController.editSave(request,bean);
        System.out.println(map.get("message"));

        //      
        PowerMockito.when(mockService.update(bean)).thenReturn(false);
        map=mockController.editSave(request,bean);
        System.out.println(map.get("message"));

        //      
        PowerMockito.when(mockService.update(ArgumentMatchers.any(MockBean.class))).thenReturn(false);
        map=mockController.editSave(request,bean);
        System.out.println(map.get("message"));
    }

}
実行結果
2018-12-30 16:43:44.556 INFO  com.suning.work.controller.MockBaseController - 1001
    !
2018-12-30 16:43:44.574 INFO  com.suning.work.controller.MockBaseController - 1001
    !
2018-12-30 16:43:44.579 INFO  com.suning.work.controller.MockBaseController - 1001
    !