標籤:
spring業務系統一般使用單例. 多層調用.
例如 A調用B,B調用C.
要測試A的方法,需要誇多層mock C的方法.
使用jmockit的NonStrictExpectations
@Servicepublic class A { @Autowired B b; public void method() { b.method(); }}
@Servicepublic class B { @Autowired IC c; public void method() { System.out.println("b=" + c.method()); }}
@Servicepublic 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(); }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
spring web 業務系統單測使用Jmockit 進行誇層mock