Using JMockit to mock autowired interface implementations

前端 未结 5 514
暖寄归人
暖寄归人 2020-12-17 18:10

We are writing JUnit tests for a class that uses Spring autowiring to inject a dependency which is some instance of an interface. Since the class under test never explicitly

5条回答
  •  情话喂你
    2020-12-17 18:53

    With the hints kindly provided above, here's what I found most useful as someone pretty new to JMockit: JMockit provides the Deencapsulation class to allow you to set the values of private dependent fields (no need to drag the Spring libraries in), and the MockUp class that allows you to explicitly create an implementation of an interface and mock one or more methods of the interface. Here's how I ended up solving this particular case:

    @Before
    public void setUp() {
    
       IMarketMakerDal theMock = new MockUp () {
    
          @Mock
          MarketMakerDcl findByMarketMakerGuid( String marketMakerGuid ) {
    
             MarketMakerDcl marketMakerDcl = new MarketMakerDcl();
             marketMakerDcl.setBaseCurrencyCode( CURRENCY_CODE_US_DOLLAR );
             return marketMakerDcl;
          }
       }.getMockInstance();
    
       setField( unitUnderTest, theMock );
    }
    

    Thanks everyone for the help.

提交回复
热议问题