模拟来自Controller类+ Mockito + Spring 4的方法调用

时间:2016-10-01 22:05:27

标签: java spring spring-boot mockito rest-assured

我试图在控制器类中模拟一个方法调用,但在尝试运行代码时,会调用原始类。 我能够成功地模拟服务层类中的方法。

我的控制器具有Util类的实例。我想模拟Util类中的方法。即使在尝试以相同的方式成功模拟服务层中的方法之后,在执行测试用例时,也会调用原始方法。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { InitializerTest.class,
        MultiHttpSecurityConfig.class, CustomerConfigTest.class,
        EmployeeConfigTest.class, DataSourcePropertiesTest.class,MyController.class })
@WebAppConfiguration
@TestExecutionListeners(listeners = { ServletTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        WithSecurityContextTestExecutionListener.class })
@ActiveProfiles("test")
public class MyControllerAbstractTest {
    private static final Logger LOG = LoggerFactory
            .getLogger(MyControllerAbstractTest.class);

    @Autowired
    public WebApplicationContext context;

    @Autowired
    public Util util;

    @Autowired
    public MyController myController;


    public static final String path = "D:/jks/";
    public static final String client1Jks = path + "client1Jks.jks";
    public static final String trustJks = path + "trustJks.jks";
    public static char[] passwd={'p','a','l'};
    KeyStore trustStore=null;

    public void setupSSLMock() throws KeyStoreException, IOException,
    NoSuchAlgorithmException, CertificateException {
        InputStream trustStoreStream = Thread.currentThread()
                .getContextClassLoader().getResourceAsStream(trustJks);
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(trustStoreStream, passwd);

        RestAssured.config = RestAssured.config()
                .sslConfig(
                        new SSLConfig().with().trustStore(trustStore).and()
                        .keystore(client1Jks, passwd.toString())
                        .allowAllHostnames());
    }

    @Before
    public void setUp() {
        //RestAssured.useRelaxedHTTPSValidation();

        if (!isSetup) {         

            this.util=(Util)context.getBean("util");
            util=Mockito.mock(Util.class);

            myController=(MyController)context.getBean(MyController.class);
            ReflectionTestUtils.setField(myController, "util",
                    Util);                  
            MockitoAnnotations.initMocks(this);
            RestAssuredMockMvc.mockMvc = MockMvcBuilders
                    .webAppContextSetup(context).apply(springSecurity())
                    .build();   
            isSetup = false;
        }
    }



    public void createValidatorMock(){
        org.mockito.Mockito.stub(
                Util
                .validateSslCertificate(org.mockito.Matchers.any())).toReturn(
                        null);
//      org.mockito.Mockito.when(
//              Util
//              .validateSslCertificate(org.mockito.Matchers.any())).thenReturn(
//                      null);  
    }

    public String invokeXMLAPI(String requestJson, String url) {

        ValidatableMockMvcResponse reponse = given().
        log().all()
                .contentType(TestConstants.APPLICATION_XML).body(requestJson)
                .when().post(url).then().statusCode(HttpServletResponse.SC_OK);
        return reponse.extract().asString();
    }
}

这是测试方法: -

    @Test
@WithMockUser(roles = "customer")
public void testXMLMessages()
        throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException {

    String url=TestConstants.XML_API;

    setupSSLMock();     
    createValidatorMock();
        invokeXMLAPI(requestJson,url)
}

以后是否有不同的方法来模拟控制器,因为它的注释方式不同。

0 个答案:

没有答案