2017-10-20 145 views
2

我有,我想驗證的方法被稱爲具有給定參數的測試:春天引導和驗證的Mockito總是正確

@Autowired 
    private Client client; 

    @Autowired 
    private OtherClient otherClient; 

    @Test 
    public void test() { 
     client.push(); 

     Mockito.verify(otherClient).publishReset(
      Mockito.anyString(), 
      Mockito.argThat(l -> l.size() == 3) 
     ); 
    } 

問題是,Mockito.verify並沒有失敗可言,我可以代替l -> l.size() == 3與任何其他大小的匹配和給定的測試將始終通過。驗證如何能夠始終傳遞我傳遞給arg的所有內容?

全部下面的例子:

@EnableConfigurationProperties 
@TestExecutionListeners(listeners = { 
    DirtiesContextTestExecutionListener.class, 
    DirtiesContextBeforeModesTestExecutionListener.class, 
    ServletTestExecutionListener.class, 
    DependencyInjectionTestExecutionListener.class, 
    MockitoTestExecutionListener.class, 
    TransactionalTestExecutionListener.class, 
    WithSecurityContextTestExecutionListener.class 
}) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) 
@EnableAspectJAutoProxy(proxyTargetClass = true) 
@ContextConfiguration(
    loader = SpringBootContextLoader.class, 
    classes = {MyApp.class, IntegrationTestContext.class}) 
@RunWith(SpringRunner.class) 
public class FooIT { 
    @Autowired 
    private Client client; 

    @Autowired 
    private OtherClient otherClient; 

    @Test 
    public void test() { 
     client.push(); 

     Mockito.verify(otherClient).publishReset(
      Mockito.anyString(), 
      Mockito.argThat(l -> l.size() == 3) 
     ); 
    } 
} 

和一個配置類:

@Configuration 
@MockBeans({ 
    @MockBean(OtherClient.class), 
}) 
public class IntegrationTestContext { 
} 

有什麼,我做錯了嗎?莫名其妙地干擾了mockito嗎?

回答

0

問題出現在垃圾回收器中,我創建了一個大的列表l,那個容器裏面有很多對象(> 30k,有很多字段),當我縮小到例如100開始正常工作。

所以基本上:不要強迫mockito使用佔用太多內存的對象(可能使用某種弱引用),例如,減少列表的大小。

1

Mockito有刺探Spring代理和最終類/方法的問題。在某些情況下,這可能會幫助:

Mockito.mock(SomeMockableType.class,AdditionalAnswers.delegatesTo(someInstanceThatIsNotMockableOrSpyable)); 

    // 
    // In your case: 
    @Test 
    public void test() {   
     OtherClient yourSpy = Mockito.mock(OtherClient.class,  
     AdditionalAnswers.delegatesTo(otherClient)); 

     client.push(); 

     Mockito.verify(yourSpy).publishReset(
     Mockito.anyString(), 
     Mockito.argThat(l -> l.size() == 3) 
     ); 
    } 

這幫助了我類似的問題,並通過此Mockito-issue Github上的啓發。