mock demo


import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

import java.math.BigDecimal;
import java.nio.charset.Charset;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.junit.MockServerRule;
import org.mockserver.matchers.MatchType;
import org.mockserver.model.Header;
import org.mockserver.model.JsonBody;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import com.alibaba.fastjson.JSON;
import com.westlakefinancial.technology.denali.payment.Application;
import com.westlakefinancial.technology.denali.payment.assist.Constants;
import com.westlakefinancial.technology.denali.payment.domain.DelTokenParam;
import com.westlakefinancial.technology.denali.payment.domain.PaymentResponse;

/**
 * /payment/tokens junit test.
 *
 * @author Westlake
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@AutoConfigureMockMvc
@ContextConfiguration()
public class TokensTest {

    @Resource
    private MockMvc mockMvc;

    /**
     * datebase xml.
     * 
     * @throws Exception
     */
    @BeforeClass
    public static void beforeClass() throws Exception {
        String dbType = "ORACLE";
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext(
                "classpath:denali-account-ws-service-datasource-test.xml");
        DataSource ds = (DataSource) app.getBean("denaliAccountWSDataSource");
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        if ("ORACLE".equals(dbType)) {
            builder.bind("java:jboss/datasources/DenaliAccountWSDSOrale", ds);
        } else {
            builder.bind("java:jboss/datasources/DenaliAccountWSDSMySql", ds);
        }
        builder.activate();
    }

    @Rule
    public MockServerRule server = new MockServerRule(this, 8081);

    /**
     * /payment/tokens test.
     * 
     * @throws Exception
     */
    @Test
    public void controllerTest() throws Exception {
        System.setProperty(Constants.KEY_SWEET_WATER_WS_URL, "http://localhost:8081");

        // Interface test Parameter
        String accNbr = "10010234";
        String company = "C-WF";
        String product = "carMortgage";
        BigDecimal fee_amt = new BigDecimal("100.6");
        String vendor = "vendor";
        String token = "tokenInfo";

        // third Interface test return value
        PaymentResponse paymentResponse = new PaymentResponse();
        paymentResponse.setConfirmation("test_Confirmation");

        // third Interface test Parameter
        DelTokenParam delTokenParam = new DelTokenParam();
        delTokenParam.setCompany(company);
        delTokenParam.setProduct(product);
        delTokenParam.setFee_amt(fee_amt);
        delTokenParam.setVendor(vendor);
        delTokenParam.setToken(token);

        // Interface in mock service
        MockServerClient mockClient = new MockServerClient("localhost", 8081);
        mockClient
                .when(request().withPath("/sweetwater/payment/delete-token/" + accNbr).withMethod("POST").withBody(
                        new JsonBody(JSON.toJSONString(delTokenParam), Charset.forName("UTF-8"), MatchType.STRICT)))
                .respond(response().withStatusCode(200).withHeader(new Header("Content-type", "application/json"))
                        .withBody(JSON.toJSONString(paymentResponse)));

        // Send request
        MvcResult result = mockMvc
                .perform(MockMvcRequestBuilders.delete("/payment/tokens").contentType(MediaType.APPLICATION_JSON_UTF8)
                        .param("accNbr", accNbr).param("fee_amt", fee_amt.toString()).param("company", company)
                        .param("vendor", vendor).param("product", product).param("token", token))
                .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();

        // Validation interface response status
        Assert.assertEquals(200, result.getResponse().getStatus());
        // Validation interface response content
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }

}

package com.westlakefinancial.technology.denali.test;

import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.junit.MockServerRule;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import com.westlakefinancial.technology.denali.payment.Application;
import com.westlakefinancial.technology.denali.payment.domain.Token;
import com.westlakefinancial.technology.denali.payment.service.IPaymentService;

/**
 * /payment/savedfundings junit test.
 *
 * @author Westlake
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@AutoConfigureMockMvc
@ContextConfiguration()
public class SavedfundingsTest2 {

    @Resource
    private MockMvc mockMvc;
    @MockBean
    private IPaymentService _IPaymentService;

    /**
     * datebase xml.
     * 
     * @throws Exception
     */
    @BeforeClass
    public static void beforeClass() throws Exception {
        String dbType = "ORACLE";
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext(
                "classpath:denali-account-ws-service-datasource-test.xml");
        DataSource ds = (DataSource) app.getBean("denaliAccountWSDataSource");
        SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
        if ("ORACLE".equals(dbType)) {
            builder.bind("java:jboss/datasources/DenaliAccountWSDSOrale", ds);
        } else {
            builder.bind("java:jboss/datasources/DenaliAccountWSDSMySql", ds);
        }
        builder.activate();
    }

    /**
     * /payment/savedfundings test.
     * 
     * @throws Exception
     */
    @Test
    public void controllerTest() throws Exception {

        String accNbr = "10010234";
        String cusName = "Westlake";
        String company = "C-WF";
        BigDecimal officialProcFee = new BigDecimal("100.6");
        String product = "carMortgage";
        String paymentDate = "2020-05-06";

        List<Token> tokenList = getMockReturnTokenList();

        Mockito.when(_IPaymentService.getSavedFundings(accNbr, cusName, company, officialProcFee, product, paymentDate))
                .thenReturn(tokenList);

        System.out.println(
                _IPaymentService.getSavedFundings(accNbr, cusName, company, officialProcFee, product, paymentDate));

        MvcResult result = mockMvc
                .perform(MockMvcRequestBuilders.get("/payment/savedfundings")
                        .contentType(MediaType.APPLICATION_JSON_UTF8).param("accNbr", accNbr).param("cusName", cusName)
                        .param("company", company).param("officialProcFee", officialProcFee.toString())
                        .param("product", product).param("paymentDate", paymentDate))
                .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn();

        System.out.println(result.getResponse().getStatus());
        Assert.assertEquals(200, result.getResponse().getStatus());
        System.out.println(result.getResponse().getContentAsString());
        Assert.assertNotNull(result.getResponse().getContentAsString());
    }

    @Rule
    public MockServerRule server = new MockServerRule(this, 8080);

    @Test
    public void controllerTest2() throws Exception {
        MockServerClient mockClient = new MockServerClient("localhost", 8080);
        String expected = "{ message: 'incorrect username and password combination' }";
        mockClient.when(request().withPath("/hello/John").withMethod("GET")
        ).respond(response().withStatusCode(200).withBody(expected));

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://localhost:8080/hello/John");
        CloseableHttpResponse response = client.execute(httpGet);
        // 验证输出是否是正确
        InputStream content = response.getEntity().getContent();
        InputStreamReader inputStreamReader = new InputStreamReader(content);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String responseText = bufferedReader.readLine();
        System.out.println(responseText);
    }

    /**
     * generate service return value
     * 
     * @return mock token list
     */
    public List<Token> getMockReturnTokenList() {
        List<Token> mockTokenList = new ArrayList<>();
        Token token = new Token();
        token.setDescription("2");
        token.setFunding_sub_type("2");
        token.setLast4("2");
        token.setName("Westlake");
        token.setPayment_vendor("2");
        token.setToken_type("2");
        token.setToken_value("2");
        mockTokenList.add(token);
        return mockTokenList;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值