首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
  • 您找到你想要的搜索结果了吗?
    是的
    没有找到

    使用Mockito修改Bean的依赖

    在使用单元测试时经常会遇到某些dependency依赖了外部资源,或者想主动绕过真正的方法执行mock返回结果而快速得到单元测试最终的期望结果,可能有以下两种场景, 对于TestCase A,设单元测试的方法是Service A的execute1方法和execute2方法,在执行execute1和execute2方法时都会调用ServiceB的不同方法,即ServiceA依赖了ServiceB;一个场景是完全对ServiceB进行Mock,如单元测试ServiceA#execute1方法时都通过Mock返回结果;一个场景是部分ServiceB的方法执行真实的业务逻辑(如查询数据库),一部分方法执行Mock返回结果,或Spy,如如单元测试ServiceA#execute2方法时,只mock ServiceB#b2结果,真正执行ServiceB#b1方法。

    02

    EasyMock PowerMock 的简单使用(with spring Autowired)


    import java.math.BigDecimal;

    import org.easymock.EasyMock;
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.easymock.PowerMock;
    import org.powermock.core.classloader.annotations.PowerMockIgnore;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    import org.springframework.aop.framework.Advised;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.util.ReflectionTestUtils;

    @RunWith(PowerMockRunner.class)
    @PrepareForTest( { PaymentReconService.class })
    @PowerMockIgnore(“org.apache.log4j.*”)
    public class PaymentGatherServiceTest extends PaymentServiceTestBase {

    @Autowired
    private GatherService gatherResultService;
    @Autowired
    private PaymentBaseDAO baseDAO;

    /**
    * 测试正常postback
    */
    public void testPaymentSucc() {
    PaymentReconService mock = mock();

    Long pbId = 10004L;
    String pbStatus = PaymentBaseEO.PB_STATUS_GATHER_SUCC;
    BigDecimal succAmount = new BigDecimal(“99.3”);

    try {
    GatherOrderRO ro = gatherResultService.processPaymentGather(pbId, pbStatus, succAmount, succAmount);
    assertNotNull(ro);

    } catch (SystemException e) {
    fail(e.getLocalizedMessage());
    } catch (BusinessException e) {
    fail(e.getBusinessCode());
    }
    EasyMock.verify(mock);
    }

    /**
    * MOCK PaymentReconService实现
    * @return
    */
    private PaymentReconService mock() {
    PaymentReconRO mockRO = new PaymentReconRO(PaymentReconRO.Status.SUCESS, “OK”);

    PaymentReconService mock = EasyMock.createMock(PaymentReconServiceImpl.class);
    EasyMock.expect(mock.paymentSuccessRecon(EasyMock.anyObject(Long.class))).andReturn(mockRO);
    EasyMock.replay(mock);
    //这里把依赖的数据注进去
    ReflectionTestUtils.s

    03
    领券