The standard way to capture arguments in JMock

Does JMock already have a built-in standard way to capture method arguments to test the argument object later with standard JUnit functions?

Something like

final CapturedContainer<SimpleMailMessage>capturedArgumentContainer = new ... context.checking(new Expectations() {{ oneOf(emailService.getJavaMailSender()).send( with(captureTo(capturedArgumentContainer))); }}); assertEquals("helloWorld", capturedArgumentContainer.getItem().getBody()); 

CapturedContainer and captureTo do not exist - this is what I am asking for.

Or do I need to implement this on my own?

+8
java junit testing jmock
source share
3 answers

I think you are running out of space. The idea is to indicate in anticipation what is about to happen, and not to capture it and check later. It will look like this:

 context.checking(new Expectations() {{ oneOf(emailService.getJavaMailSender()).send("hello world"); }}); 

or perhaps for a weaker state,

 context.checking(new Expectations() {{ oneOf(emailService.getJavaMailSender()).send(with(startsWith("hello world"))); }}); 
+5
source share

You can do this by introducing a new Matcher that captures the argument when calling match. This can be obtained later.

 class CapturingMatcher<T> extends BaseMatcher<T> { private final Matcher<T> baseMatcher; private Object capturedArg; public CapturingMatcher(Matcher<T> baseMatcher){ this.baseMatcher = baseMatcher; } public Object getCapturedArgument(){ return capturedArg; } public boolean matches(Object arg){ capturedArg = arg; return baseMatcher.matches(arg); } public void describeTo(Description arg){ baseMatcher.describeTo(arg); } } 

Then you can use this when setting your expectations.

 final CapturingMatcher<ComplexObject> captureMatcher = new CapturingMatcher<ComplexObject>(Expectations.any(ComplexObject.class)); mockery.checking(new Expectations() {{ one(complexObjectUser).registerComplexity(with(captureMatcher)); }}); service.setComplexUser(complexObjectUser); ComplexObject co = (ComplexObject)captureMatcher.getCapturedArgument(); co.goGo(); 
+10
source share

I found myself in a similar situation, wanting to check the field of the object passed to the layout. Instead of using an invader, as Mark shows, I tried what I consider more convenient for JMock. Code adjusted for your use case:

 mockery.checking(new Expectations() {{ oneOf(emailService.getJavaMailSender()).send( with(Matchers.<SimpleMailMessage>hasProperty("body", equal("Hello world!")))); }}); 

I understand that this has limitations, but in most cases, controllers should be able to check the object in question. Hope this helps.

0
source share

All Articles