I have some problems with the jersey test framework. If i use the #Before and #After annotations, then the target method throws a NullPointerException.
I thought JerseyTest works with JUnit? Where is my problem?
Jersey: 2.12
JUnit: 4.11
Code that fails:
public class MyResourceTest extends JerseyTest {
#Before
public void setUp() { }
#After
public void tearDown() { }
#Override
protected Application configure() {
return new ResourceConfig(MyResource.class);
}
#Test
public void SHOULD_RETURN_BAD_REQUEST() throws IOException {
System.out.println(target("myPath"));
assertEquals(1, 1);
}
}
Result:
java.lang.NullPointerException at
org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:566) at
org.glassfish.jersey.test.JerseyTest.target(JerseyTest.java:580) at
foo.bar.MyResourceTest.SHOULD_RETURN_BAD_REQUEST(MyResourceTest.java:43)
Code that works:
public class MyResourceTest extends JerseyTest {
#Override
protected Application configure() {
return new ResourceConfig(MyResource.class);
}
#Test
public void SHOULD_RETURN_BAD_REQUEST() throws IOException {
System.out.println(target("myPath"));
assertEquals(1, 1);
}
}
Result:
JerseyWebTarget { http://localhost:9998/myPath }
Your methods seem to override some important initialization made in parent JerseyTest.
Try to name them differently. E.g.:
#Before
public void setUpChild() { }
#After
public void tearDownChild() { }
I came here because I was using JUnit 5 and it seems that it wasn't seeing the #Before and #After annotations on the JerseyTest setup/tearDown methods. I had to override them and use the new JUnit 5 annotations
public class MyResourceTest extends JerseyTest {
#BeforeEach
#Override
public void setUp() throws Exception {
super.setUp();
}
#AfterEach
#Override
public void tearDown() throws Exception {
super.tearDown();
}
#Override
protected Application configure() {
return new ResourceConfig(MyResource.class);
}
#Test
public void SHOULD_RETURN_BAD_REQUEST() throws IOException {
System.out.println(target("myPath"));
assertEquals(1, 1);
}
}
Related
This is the method that i am trying to test:
#Singleton
public class PriorityJobQueueService {
public void registerIndividualJob(String jobCode) throws InterruptedException {
List<PriorityJobMapDTO> priorityJobMapDTOS = CDI.current().select(JobGroupsMasterService.class).get().getJobForCronScheduler(jobCode);
priorityJobMapDTOS = validateStrictJobs(priorityJobMapDTOS);
triggerJob(priorityJobMapDTOS);
}
}
This is the skeleton structure of my test file:
#RunWith(MockitoJUnitRunner.class)
public class PriorityJobQueueServiceTest {
#Before
public void beforeTest() throws Exception {
fixture = new Fixture();
}
#Test
public void registerIndividualJob_SUCCESS() throws InterruptedException {
}
private class Fixture {
#InjectMocks
PriorityJobQueueService priorityJobQueueService;
private Fixture() throws Exception {
MockitoAnnotations.initMocks(this);
}
}
}
Now, what i need to do is mock CDI.current.select() statement so that i can run the test.
The only things i've found so far is having to add additional dependencies to my project with the following libraries:
Quarkus
cdi-unit
So are there any other ways to achieve this?
I would change the code to be composable. That's the entire point of Dependency Injection :)
#Singleton
public class PriorityJobQueueService {
#Inject
private JobGroupsMasterService jobGroupsMasterService;
public void registerIndividualJob(String jobCode) throws InterruptedException {
List<PriorityJobMapDTO> priorityJobMapDTOS = jobGroupsMasterService.getJobForCronScheduler(jobCode);
priorityJobMapDTOS = validateStrictJobs(priorityJobMapDTOS);
triggerJob(priorityJobMapDTOS);
}
}
Now your test will look like
#RunWith(MockitoJUnitRunner.class)
class PriorityJobQueueServiceTest {
#Mock
private JobGroupsMasterService jobGroupsMasterService;
#InjectMocks
private PriorityJobQueueService priorityJobQueueService;
#Test
void registerIndividualJob_SUCCESS() throws InterruptedException {
priorityJobQueueService.registerIndividualJob(...);
}
}
cheers, good luck!
When I'm trying to mock a static method with a String input, mocked stub is getting executed when I give a specific String, but when I use anyString(), it does not work as expected.
public class Foo {
public static String staticInput(String s) {
System.out.println("staticInput called");
return "static " + s;
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest({Foo.class})
public class TestMockito {
#Test
public void test1() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.doReturn("dummyStaticStub").when(Foo.class, "staticInput", "1");
System.out.println(Foo.staticInput("1"));
}
#Test
public void test2() throws Exception {
PowerMockito.spy(Foo.class);
PowerMockito.doReturn("dummyStaticIn").when(Foo.class, "staticInput", anyString());
System.out.println(Foo.staticInput("1"));
}
}
test1 prints:
dummyStaticStub
test2 prints:
staticInput called
static 1
You can change the approach a little and use PowerMockito.mockStatic instead
#RunWith(PowerMockRunner.class)
#PrepareForTest({Foo.class})
public class TestMockito {
#Test
public void test1() throws Exception {
PowerMockito.mockStatic(Foo.class);
Mockito.when(Foo.staticInput("1")).thenReturn("dummyStaticStub");
System.out.println(Foo.staticInput("1"));
}
#Test
public void test2() throws Exception {
PowerMockito.mockStatic(Foo.class);
PowerMockito.when(Foo.staticInput(anyString())).thenReturn("dummyStaticIn");
System.out.println(Foo.staticInput("1"));
}
}
Reference Using PowerMock with Mockito: Mocking Static Method
My application context is not closed after test method.
I use Junit 5.3.1, spring 5.1.0.RELEASE for Selenium WebDriver tests.
This is my bean:
#Configuration
public class WebDriverConfig {
// ... Some Code ...
#Bean(destroyMethod = "quit")
#Primary
public DelegatingWebDriver cleanWebDriver(WebDriver driver) throws Exception {
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
return new DelegatingWebDriver(driver);
}
// ... Some more code ...
}
This is my class:
#ExtendWith({SpringExtension.class})
#ContextConfiguration(classes = { WebDriverConfig.class, LoggerConfig.class, EmailConfig.class})
#TestExecutionListeners(listeners= {ScreenshotTaker.class, DependencyInjectionTestExecutionListener.class, TestListener.class})
#DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class BasicScenariosIT {
#Inject
private DelegatingWebDriver driver;
#SuppressWarnings("unused")
#Inject
private URI baseUrl;
#Inject
private Logger logger;
private DelegatingExtentTest testCase;
// ... Some tests ...
}
I expect the line:
#DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
to close the application context and fire up the line:
#Bean(destroyMethod = "quit")
In my case, call method "quit" close the browser and start a new one. However it doesn't seem to happen.
Would appreciate the help
Well, I found a workaround.
I implemented spring test listeners, and in the listener I marked the context as dirty, instead of relying on the #DirtiesContext annotation.
The listener looks like this:
#ExtendWith({SpringExtension.class})
#ContextConfiguration(classes = { WebDriverConfig.class, LoggerConfig.class})
#TestExecutionListeners(listeners= {DependencyInjectionTestExecutionListener.class})
public class RunnerExtension extends AbstractTestExecutionListener {
#Autowired
protected Logger logger;
#Autowired
protected DelegatingWebDriver driver;
#Override
public void beforeTestClass(TestContext testContext) throws Exception {
testContext.getApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this);
}
#Override
public void beforeTestMethod(TestContext testContext) throws Exception {
// .. some code here ..
}
#Override
public void beforeTestExecution(TestContext testContext) throws Exception {
// .. some code here ..
}
#Override
public void afterTestExecution(TestContext testContext) throws Exception {
// .. some code here ..
}
#Override
public void afterTestMethod(TestContext testContext) throws IOException {
// .. some code here ..
testContext.markApplicationContextDirty(HierarchyMode.EXHAUSTIVE);
}
#Override
public void afterTestClass(TestContext testContext) throws IOException {
// .. some code here ..
}
}
The important code line is:
testContext.markApplicationContextDirty(HierarchyMode.EXHAUSTIVE);
It marks the context as dirty and a new context will be created in the next session.
I am writing a JUnit test case for a Route class. I'm facing a problem while mocking ServiceClass inside the Processor class.
public class SaveRouteTest extends CamelTestSupport {
private Exchange exchange;
protected ProducerTemplate template;
private SaveRequestBuilder saveRequestBuilder;
private SaveRoute route;
private SaveProcessor saveProcessor;
private ApplicationContext springContext = createApplicationContext();
#Mock
SaveServiceClient saveServiceClient;//Not able to mock this class
#BeforeClass
public void prepareTestCamelContext() throws Exception {
route = springContext.getBean("saveRoute", saveRoute.class);
saveProcessor = springContext.getBean("saveProcessor",
SaveProcessor.class);
saveRequestBuilder = springContext.getBean("saveRequestBuilder",
SaveRequestBuilder.class);
}
#BeforeMethod
public void init() throws SQLException, ServiceException {
MockitoAnnotations.initMocks(this);
exchange = new DefaultExchange(context);
}
#Override
protected RouteBuilder[] createRouteBuilders() throws Exception {
template = context.createProducerTemplate();
return new RouteBuilder[]{route};
}
#Test
public void testHotelCommitTransactionRouteSuccessReturn() throws
Exception {
when(saveServiceClient.invokeServiceWithName(anyObject()).
thenReturn("Response");
exchange.getIn().setBody("Request detail");
exchange = template.send("direct:SaveRoute",exchange);
}
protected ApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("classpath*:config/spring/testContext.xml");
}
}
#Component
public class SaveRoute extends SPRouteBuilder {
#Autowired
private SaveProcessor saveProcessor;
#Override
public void configure() throws Exception {
from("direct:SaveRoute")
.routeId("save")
.to("direct:ProcessSaveFlow")
.end();
from("direct:ProcessSaveFlow")
.process(saveProcessor)
.end();
}
}
public class SaveProcessor implements Processor {
#Autowired
SaveServiceClient saveServiceClient;
#Override
public void process(Exchange exchange) throws Exception {
//This line of code not able to mock
String response = saveServiceClient.invokeServiceWithName(exchange);
exchange.getIn().setBody(response);
}
}
How to resolve mocking of saveServiceClient.invokeServiceWithName? The debugger is always going inside this method. I tried using both mock objects and an injected mock. I can't make the method call directly.
You are creating a mock object, however you are not injecting it anywhere (normally you are doing it with #InjectMocks annotation - read about it).
I think there are several possibilities:
Provide a #MockBean object, which will be considered as a bean candidate in context.
There is a code example for mocking beans.
#RunWith ( CamelSpringRunner.class )
#SpringBootTest
public class RouteBuilderTest extends CamelSpringTestSupport {
#Autowired
private ApplicationContext applicationContext;
#MockBean
private ServiceClient serviceClient;
#Override
public void setUp() throws Exception {
MockitoAnnotations.initMocks( this );
super.setUp();
}
#Override
public void tearDown() {
}
#Test
public void test() {
when( serviceClient.doStuff() ).thenReturn( "mockedResponse" );
}
}
Mock SaveProcessor and inject it to Route class - you shouldn't take care of ServiceClient, because you are trying to test too much. Tests for SaveProcessor should be separated, tests for route don't need this logic.
I have created a bean with method that I want to test. Unfortunately it's a bean with a PostConstruct annotation in it. I don't want to call the PostConstruct method.
How can I do this?
I've tried 2 different ways (as shown in the example below) but none working; init() still gets called.
Can someone please give me a detailed example of how to do this?
DirBean.java
#Singleton
#Startup
public class DirBean implements TimedObject {
#Resource
protected TimerService timer;
#PostConstruct
public void init() {
// some code I don't want to run
}
public void methodIwantToTest() {
// test this code
}
}
MyBeanTest.java
public class MyBeanTest {
#Tested
DirBean tested;
#Before
public void recordExpectationsForPostConstruct() {
new Expectations(tested) {
{
invoke(tested, "init");
}
};
}
#Test
public void testMyDirBeanCall() {
new MockUp<DirBean>() {
#Mock
void init() {
}
};
tested.methodIwantToTest();
}
}
MyBeanTest2.java (WORKS)
public class MyBeanTest2 {
#Tested
DirBean tested;
#Before
public void recordExpectationsForPostConstruct() {
new MockUp<DirBean>() {
#Mock
void init() {}
};
}
#Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}
MyBeanTest3.java (WORKS)
public class MyBeanTest3 {
DirBean dirBean = null;
#Mock
SubBean1 mockSubBean1;
#Before
public void setupDependenciesManually() {
dirBean = new DirBean();
dirBean.subBean1 = mockSubBean1;
}
#Test
public void testMyDirBeanCall() {
dirBean.methodIwantToTest();
}
}
MyBeanTest4.java (FAILS with NullPointerException on invoke())
public class MyBeanTest4 {
#Tested
DirBean tested;
#Before
public void recordExpectationsForCallsInsideInit() {
new Expectations(tested) {
{
Deencapsulation.invoke(tested, "methodCalledfromInit", anyInt);
}
};
}
#Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}
Move definition of MockUp type to #Before method:
public class MyBeanTest {
#Tested
DirBean tested;
#Before
public void recordExpectationsForPostConstruct() {
new MockUp<DirBean>() {
#Mock
void init() {
}
};
}
#Test
public void testMyDirBeanCall() {
tested.methodIwantToTest();
}
}