I want to selectively update fields in a table using spring jpa. According to https://stackoverflow.com/a/39746931/2739681 this should be possible with a simple function like:
public TestEntity update(UUID uuid, String string2new) {
TestEntity testEntity = testEntityRepository.getOne(uuid);
testEntity.setString2(string2new);
return testEntityRepository.save(testEntity);
}
where TestEntity is (omitted getter and setter):
#Entity
public class TestEntity {
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Id
#Column(columnDefinition = "BINARY(16)")
private UUID id;
private String string;
private String string2;
}
However, my test code:
#Test
public void selectiveUpdate2() {
TestEntity testEntity = testEntityRepository.save(TestEntity.builder().string("lulu").string2("lala").build());
System.out.println(testEntityRepository.findAll());
testEntityService.updateString2(testEntity.getId(), "lele");
System.out.println(testEntityRepository.findAll());
}
However I got an exception as following:
[TestEntity(id=61a24efc-877f-4a89-9e75-a9933fe7c04c, string=lulu, string2=lala)]
org.hibernate.LazyInitializationException: could not initialize proxy [com.example.test_db_zeug.TestEntity#61a24efc-877f-4a89-9e75-a9933fe7c04c] - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:309)
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45)
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95)
at com.example.test_db_zeug.TestEntity$HibernateProxy$GilcmZfo.setString2(Unknown Source)
at com.example.test_db_zeug.TestEntityService.update(TestEntityService.java:39)
at com.example.test_db_zeug.TestDbZeugApplicationTests.selectiveUpdate(TestDbZeugApplicationTests.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Related
I have been writing unit tests for Spring reactive app. I am trying to stub method response which returns Mono. I tried with samples on the net. But it is giving Null pointer exception. If we can't stub Mono types with Mockito , Please suggest me alternative way.
Complete code is available in below repository
https://github.com/NarayanaBojja/example-service
public Mono<Person> getName() {
Mono<Person> nameMono = name();
return nameMono.flatMap(per -> Mono.just(per)).onErrorResume(error -> {
return Mono.error(new RuntimeException("Name not found"));
});
}
public Mono<Person> name() {
Person person = new Person();
person.setName("Narayana");
return Mono.just(person);
}
Unit test case for the above code is
#RunWith(SpringRunner.class)
#SpringBootTest
public class DemoApplicationTests {
#Autowired
private ExampleService exampleService;
#Test
public void getNameTest() {
Person person = new Person();
person.setName("Narayana");
Mono<Person> nameMono = Mono.just(person);
given(this.exampleService.name()).willReturn(nameMono);
StepVerifier.create(exampleService.getName()).expectNext(person).verifyComplete();
}
}
I am getting below Exception
java.lang.NullPointerException
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:801)
at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:772)
at reactor.test.DefaultStepVerifierBuilder.verifyComplete(DefaultStepVerifierBuilder.java:644)
at com.example.demo.DemoApplicationTests.getNameTest(DemoApplicationTests.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
A newbie to Spring boot running integration testing. Using exchange method of TestRestTemplate I am unable to pass LocalDateTime request params to test method. Here's my MemberController method and MemberControllerTest method. I guess it has to do with the date and format because the same exchange method works when I test for get member with id as integer.
#Test
#Transactional
public void getTopMembersss() throws Exception {
LocalDateTime startTime = LocalDateTime.of(2015, Month.JULY, 29, 19, 30, 40);
LocalDateTime endTime = LocalDateTime.of(2019, Month.JANUARY, 01, 19, 30, 40);
ResponseEntity<List<TopMemberDTO>> response = template.exchange(
"/api/member/top-member?startTime={startTime}&endTime={endTime}", HttpMethod.GET, null,
new ParameterizedTypeReference<List<TopMemberDTO>>() {
}, startTime.toString(), endTime.toString());
// , "2018-12-31T12:12:12", "2018-12-31T12:12:12"
Assert.assertEquals(200, response.getStatusCode().value());
}
#GetMapping(path = "/api/member/top-member?startTime={startTime}&endTime={endTime}")
public ResponseEntity<List<TopMemberDTO>> getTopMembers(
#RequestParam(value = "startTime", required = true) #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime startTime,
#RequestParam(value = "endTime", required = true) #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime endTime) {
List<TopMemberDTO> topDrivers = new ArrayList<>();
/**
* Your Implementation Here.
*
*/
topDrivers = memberService.findTopMembersCount(startTime, endTime);
if (topDrivers.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(topDrivers);
}
}
java.lang.AssertionError: expected:<200> but was:<400>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:645)
at org.junit.Assert.assertEquals(Assert.java:631)
at com.thankgod.controller.MemberControllerTest.getTopMembersss(MemberControllerTest.java:137)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
change
#GetMapping(path = "/api/member/top-member?startTime={startTime}&endTime={endTime}")
to
#GetMapping(path = "/api/member/top-member")
I've a MongoDb repository with a query to find a document by its Id field (which also has #Id annotation).
public interface CustomerRepository extends MongoRepository<Customer,
String> {
public Customer findById(String id);
}
What I don`t understand is why this is correct when testing the repository
#Test
public void testFindById() {
this.customerRepository.save(new Customer("4", "Anna", "Michigan"));
assertNotNull(customerRepository.findById("4"));
}
but when testing the controller whose method use the findById() method
#Controller
public class CustomerController {
#Autowired
private CustomerRepository customerRepository;
public boolean existsId(String id) {
return this.customerRepository.findById(id) != null;
}
}
I get an AssertionError
#RunWith(SpringRunner.class)
#SpringBootTest
#TestPropertySource(locations = "classpath:test.properties")
public class CustomerControllerIT {
#Autowired
private CustomerController customerController;
#Test
public void testExistsIdTrue() {
CustomerDto customerDto = new CustomerDto("2", "Mark", "New York");
assertTrue(customerController.existsId("2"));
}
}
I cannot understand why that happens, when in respository and controller we are using the same method.
This is the trace:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
at account.persistence.controllers.CustomerControllerIT.testExistsIdTrue(CustomerControllerIT.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
When I use JUnit, I run into this error:
java.lang.NullPointerException at
com.mpdidb.mapper.TbUserServiceTest.selectByPrimaryKeyTest(TbUserServiceTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
And this is my JUnit code:
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {RootConfig.class})
public class TbUserServiceTest
{
#Autowired
private static TbUserService tbUserService;
#Test
public void selectByPrimaryKeyTest()
{
String userId = "wusuodai";
TbUser tbUser = tbUserService.selectByPrimaryKey(userId);
System.out.println(tbUser.getUserName());
}
}
How to solve this error?
Static fields can not be autowired by field injection. Consider using setter injection.
private static TbUserService tbUserService;
#Autowired
public void setTbUserService(TbUserService tbUserService){
this.tbUserService = tbUserService;
}
I'm using Spring 4.3.8.RELEASE, JUnit 4.12 ,and Mockito 1.10.18. I'm trying to test whether my "publishEvent" method is called from below ...
#Service
#Transactional
public class MyObjectServiceImpl implements MyObjectService, ApplicationEventPublisherAware
{
private ApplicationEventPublisher publisher;
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher)
{
this.publisher = publisher;
}
...
public void myMethod(MyObject obj) {
...
publisher.publishEvent(new ThirdPartyUpdateUserEvent(userId));
publisher.publishEvent(new ThirdPartyUpdateObjectEvent(objectId));
and then in my JUnit test I have
#Before
public final void setup()
{
eventPublisher = Mockito.mock(ApplicationEventPublisher.class);
((ApplicationEventPublisherAware) myObjectService).setApplicationEventPublisher(eventPublisher);
((ApplicationEventPublisherAware) userService).setApplicationEventPublisher(eventPublisher);
} // setup
#Test
...
// Verify first call
final ArgumentCaptor<ThirdPartyUpdateUserEvent> argument2 = ArgumentCaptor.forClass(ThirdPartyUpdateUserEvent.class);
Mockito.verify(eventPublisher, Mockito.times(2)).publishEvent(argument2.capture());
Assert.assertEquals("Failed to call method with proper argument.", userId, argument2.getValue().getUserId());
// Verify second call
final ArgumentCaptor<ThirdPartyUpdateMyObjectEvent> argument = ArgumentCaptor.forClass(ThirdPartyUpdateMyObjectEvent.class);
Mockito.verify(eventPublisher, Mockito.times(2)).publishEvent(argument.capture());
Assert.assertEquals("Failed to call method with proper argument.", objectId, argument.getValue().getObjectId());
Through debugging, I can see that each of the "publishEvent" methods is called exactly once, yet when I go to verify the calls I get the error for the first "verify" line in my #Test
java.lang.ClassCastException: org.mainco.subco.ThirdPartyItem.domain.ThirdPartyUpdateMyObjectEvent cannot be cast to org.mainco.subco.ThirdPartyItem.domain.ThirdPartyUpdateUserEvent
at com.follett.fdr.lycea.lms.MyObject.test.service.MyObjectServiceDWRTest.testArchiveMyObject(MyObjectServiceDWRTest.java:1234)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
What's the right way to verify two consecutive calls to my mocked publish service?
Instead of creating an ArgumentCaptor for ThirdPartyUpdateUserEvent and
ThirdPartyUpdateMyObjectEvent, why not create one captor for Object:
final ArgumentCaptor<Object> argumentsCaptor = ArgumentCaptor.forClass(Object.class);
Or better yet, whatever common interface ThirdPartyUpdateUserEvent and ThirdPartyUpdateMyObjectEvent implement (ThirdPartyUpdateEvent?)
Now you can do this:
Mockito.verify(eventPublisher, Mockito.times(2)).publishEvent(argumentsCaptor.capture());
List<Object> arguments = argumentsCaptor.getAllValues();
assertTrue(arguments.get(0) instanceof ThirdPartyUpdateUserEvent);
assertTrue(arguments.get(1) instanceof ThirdPartyUpdateMyObjectEvent);
And test those arguments for whatever other conditions you need.