春天引导和验证的Mockito总是正确
问题描述:
我有,我想验证的方法被称为具有给定参数的测试:春天引导和验证的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吗?
答
问题出现在垃圾回收器中,我创建了一个大的列表l
,那个容器里面有很多对象(> 30k,有很多字段),当我缩小到例如100开始正常工作。
所以基本上:不要强迫mockito使用占用太多内存的对象(可能使用某种弱引用),例如,减少列表的大小。
答
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上的启发。