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)
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)
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)
I need some help with my code. I have this controller:
#RestController
#RequestMapping("/center")
public class CenterController {
private final Logger log = LoggerFactory.getLogger(CenterController.class);
#Autowired
private CenterService service;
#GetMapping(value = "/{idCenter}", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(code = HttpStatus.OK)
public Center findBy(#PathVariable String idCenter) {
log.debug("findBy --> Getting a center by id.");
return service.findOne(idCenter);
}
and this testing class
#RunWith(SpringRunner.class)
#SpringBootTest(classes = ServiceTestConfiguration.class)
public class CenterControllerTest {
private final Logger log = LoggerFactory.getLogger(CenterControllerTest.class);
private MockMvc mockMvc;
private ObjectMapper mapper;
private Center center;
private Center center2;
private ArrayList<Center> listCenters;
#MockBean
private CenterService centerService;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setup() {
log.debug("CenterControllerTest --> setup()");
mapper = new ObjectMapper();
loadData();
CenterController centerController = new CenterController();
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#After
public void teardown() {
log.debug("CenterControllerTest --> teardown()");
centerService.deleteAll();
}
private void loadData() {
log.debug("centerControllerTest --> loadData() Loading test data");
center = new Center();
center.setIdCenter("1");
center.setCenterCode("123");
center.setStreet("Test street");
center.setPopulation("Test population");
center.setProvince("Test province");
center.setPostalCode("Test postal code");
center.setTelephone((long) 999888777);
center.setActive(true);
centerService.save(center);
}
#Test
public void getCenterByIdTest2() throws Exception{
when(centerService.findOne("1")).thenReturn(new Center());
mockMvc.perform(get("/center")
.param("idCenter", "1"))
.andExpect(status().isOk());
}
When I try to test it, it gives me the following trace
java.lang.AssertionError: Status expected:<200> but was:<404> at
org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at
org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at
org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at
org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at
com.api.controller.CenterControllerTest.getCenterByIdTest2(CenterControllerTest.java:90)
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.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: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: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)
I think it's a configuration problem, can anyone notice where is the code failure?
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.
I'm trying to create a very basic unit test for a spring mvc rest controller using the MockMvcBuilders.standaloneSetup method. I keep getting a 404 error. Below I list my Test application context, my test class, and my controller and the full stack trace. Any guidance is appreciated.
#Configuration
public class TestContext
{
#Bean
public Service service()
{
return mock(Service.class);
}
}
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={TestContext.class})
#WebAppConfiguration
public class TestUsingWebAppContextSetUp
{
private MockMvc mockMvc;
#Autowired
private Service service;
#Before
public void setUp()
{
mockMvc = MockMvcBuilders.standaloneSetup(MyController.class)
.build();
}
#Test
public void test() throws Exception
{
mockMvc.perform(get("/search?phoneNumber=5551112222"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE));
}
}
public class MyController
{
#Autowired
private Service service;
#RequestMapping("/search")
public List<SearchResult> search(#RequestParam(value="phoneNumber") String phoneNumber)
{
System.out.println("search called");
Search search = new Search();
search.setPhoneNumber(phoneNumber);
return service.search(search);
}
}
java.lang.AssertionError: Status expected:<200> but was:<404> at
org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at
org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at
org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:653)
at
org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
at
com.mycompany.TestUsingWebAppContextSetUp.test(TestUsingWebAppContextSetUp.java:41)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at
org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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:675)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The javadoc of MockMvcBuilders.standaloneSetup states
Build a MockMvc by registering one or more #Controller's instances and
configuring Spring MVC infrastructure programmatically. This allows
full control over the instantiation and initialization of controllers,
and their dependencies, similar to plain unit tests while also making
it possible to test one controller at a time.
So you would use it as
mockMvc = MockMvcBuilders.standaloneSetup(new MyController()).build();
registering an actual instance. If you need this to be a Spring managed instance (which you probably do considering it has an #Autowired field), you'd have to get it from the ApplicationContext.