spring业务系统一般使用单例. 多层调用.
例如 A调用B,B调用C.
要测试A的方法,需要夸多层mock C的方法.
使用jmockit的NonStrictExpectations
@Service public class A { @Autowired B b; public void method() { b.method(); } }
@Service public class B { @Autowired IC c; public void method() { System.out.println("b=" + c.method()); } }
@Service public class C implements IC { @Override public Integer method() { System.out.println("123"); return 1; } }
public interface IC { public Integer method(); }
@RunWith(SpringJUnit4ClassRunner.class) @TransactionConfiguration(transactionManager = "kuaipayTransactionManager", defaultRollback = true) @Transactional @ContextConfiguration(locations = { "classpath:kuaipay-api-impl-test-application.xml" }) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) public class JmockitTestMock { @Autowired A a; // 对接口进行mock,对应dubbo @Autowired IC ic; // 夸层 mock.直接把class给替换了. jmockit的神力 @Test public void testMockit() { new <span style="color:#ff0000;">NonStrictExpectations</span>(ic) { { ic.method(); result = Integer.valueOf(5); } }; a.method(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-16 11:33:11