I want to mock the mail sending not to send mail in unit testing.
My code is below:
#Component("utilityRoutes")
public class UtilityRoutes extends RouteBuilder {
#Override
public void configure() throws Exception {
from("seda:sendEmail")
.routeId("utilityRoutes")
.setHeader("from", simple("{{email.from}}"))
.setHeader("contentType", constant("text/plain;charset=UTF-8"))
.choice()
.when(header(Constants.HEADER_EMAIL_TARGET).isEqualTo("AAA"))
.setHeader("to", simple("{{recipients-a}}"))
.when(header(Constants.HEADER_EMAIL_TARGET).isEqualTo("BBB"))
.setHeader("to", simple("{{recipients-b}}"))
.end()
.to("{{email.url}}")
.id("emailUrl");
}
}
My Test Case is:
#RunWith(CamelSpringBootRunner.class)
#SpringBootTest
#TestPropertySource(locations = "classpath:application.properties")
#ContextConfiguration(classes = { RailMLExport.class })
#DirtiesContext
public class UtilityRoutesTest extends CamelTestSupport {
#Autowired
CamelContext camelContext;
#Produce(uri = "seda:sendEmail")
ProducerTemplate producerTemplate;
#EndpointInject(uri="mock:emailEndpoint")
MockEndpoint mailEndpoint;
#Override
public boolean isUseAdviceWith() {
return true;
}
#Override
public String isMockEndpoints() {
return "*";
}
#Test
public void testSendAndReceiveMail() throws Exception {
camelContext.getRouteDefinition("utilityRoutes").adviceWith(camelContext, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
weaveById("emailUrl").after().to("mock:emailEndpoint");
}
}
);
camelContext.start();
Collection<Endpoint> endpoints = camelContext.getEndpoints();
for (Endpoint endpoint : endpoints) {
System.err.println(endpoint.getEndpointUri());
}
mailEndpoint.expectedMessageCount(1);
mailEndpoint.expectedBodyReceived();
Map<String,Object> headers = new HashMap<>();
headers.put(Constants.HEADER_EMAIL_TARGET,"AAA");
headers.put(Constants.HEADER_EMAIL_SUBJECT, "CCC");
producerTemplate.requestBodyAndHeaders("seda:sendEmail", "test", headers);
mailEndpoint.assertIsSatisfied();
}
}
I give error as follows.
java.lang.IllegalStateException: ProducerTemplate has not been started
at org.apache.camel.impl.DefaultProducerTemplate.getProducerCache(DefaultProducerTemplate.java:689)
at org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:148)
at org.apache.camel.impl.DefaultProducerTemplate.sendBodyAndHeaders(DefaultProducerTemplate.java:267)
at org.apache.camel.impl.DefaultProducerTemplate.requestBodyAndHeaders(DefaultProducerTemplate.java:317)
at org.apache.camel.impl.DefaultProducerTemplate.requestBodyAndHeaders(DefaultProducerTemplate.java:313)
at fi.vr.h.ivu.integration.railmlexport.routes.UtilityRoutesTest.testSendAndReceiveMail(UtilityRoutesTest.java:89)
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: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.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
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)
Either overwrite isMockEndpointsAndSkip or use adviceWith as you mentioned and skip it in that AdviceWithRoute. You can even intercept your exchange and call skipSendToOriginalEndpoint from there. Different possible ways to accomplish what you want.
A further note: You probably shouldn't use "*" in isMockEndpoints (or isMockEndpointsAndSkip), except you want to mock every route. Just mention the routes you really want to mock. This way it is more clear for other programmers watching your code what you really are mocking and what not.
Related
I want to test an API call I make - where I use the Retrofit2 framework for.
My code is the following:
API Utilities File:
package com.example.nsi_prediction.API
import com.example.nsi_prediction.API.RetrofitClient.getClient
object ApiUtils {
/**
* Defines the used utilities for the Retrofit Client
*/
const val BASE_URL = "http://10.0.2.2:8080/"
fun getAPIService(): APIService {
return getClient(BASE_URL)!!.create(
APIService::class.java)
}
}
Retrofit Client Object
object RetrofitClient {
/**
* Initializes the retrofit Client
*/
private var retrofit: Retrofit? = null;
fun getClient(baseUrl: String?): Retrofit? {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}
API Service File:
interface APIService {
/**
* All specific API calls are defined here
*/
#POST("/api/v1/gps")
#Headers(
"Accept: application/json",
"Content-type:application/json"
)
fun sendGPS(#Body GPS: GPS): Call<GPS>
}
I have written my test like this:
#RunWith(JUnit4::class)
class RequestTest {
#InjectMocks
lateinit var RetrofitClient: RetrofitClient;
#InjectMocks
lateinit var gps_model: GPS;
#Mock
lateinit var APIs: APIService;
#InjectMocks
lateinit var ApiUtils: ApiUtils;
#Before
fun setUp() {
MockitoAnnotations.initMocks(this)
Mockito.`when`<Any>(APIs.sendGPS(gps_model).execute().message())
.thenReturn("{'x': '1.4'}")
}
#Test
fun setGitHubTaskTest_ReturnsTrue() {
assertThat(APIs.sendGPS(gps_model).execute().message(), containsString("1.4"))
}
}
But when I run the test I get a Null Pointer Exception:
java.lang.NullPointerException
at com.example.nsi_prediction.RequestTest.setUp(RequestTest.kt:36)
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.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
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 want to jsut test if the logic in which the different files talk to each other works. How can I test my API Call functions correctly?
Let's say I want to verify if the ShopCart.itemUpdated() is called:
data class ShopCart(val item: Item)
data class Item(val price: Int)
class ShopCartController(private val cart: ShopCart) {
fun updateCart() {
cart.itemUpdated()
}
fun ShopCart.itemUpdated() = copy(
item = item.copy(price = 20)
)
}
class ShopCartControllerTest {
#Test
fun test() {
val cart = ShopCart(Item(0))
val cartSpy = spy(cart)
val controller = ShopCartController(cartSpy)
controller.updateCart()
with(controller) {
verify(cartSpy).itemUpdated()
}
}
However, this test fails and throws java.lang.NullPointerException.
java.lang.NullPointerException
at com.test.ShopCartController.itemUpdated(Test.kt:28)
at com.test.ShopCartControllerTest.testMe(Test.kt:17)
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.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
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)
Is it possible to verify a class extension function is called? I have tried several mocking frameworks (e.g. mockito, mockk), no luck. Do you guys have any ideas?
Impl.java
------------------------------------------------------------------
public List<SearchDTO> findByCriteria(SearchCriteriaDTO SearchCriteriaDTO) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Search> query = builder.createQuery(Search.class);
Root<Search> repls = query.from(Search.class);
final int QUERY_LIMIT = Integer.parseInt(queryLimit);
List<UUID> statusIds = SearchCriteriaDTO.getStatusIds();
if (statusIds != null && !statusIds.isEmpty()) {
predicates.add(builder.and(repl.get("statusId").in(statusIds)));
}
-----------------------------
below is the test class for impl class.
impltest.java
---------------------------
//mocking the services.
#Mock
private SearchMapper SearchMapper;
#Mock
private SearchRepository SearchRepository;
#Mock
private CriteriaBuilder criteriaBuilder;
#Mock
private Root root;
#Mock
private EntityManager entityManager;
#Rule
public ExpectedException thrown = ExpectedException.none();
#Mock
CriteriaQuery<Search> criteriaQuery;
#Mock
Root<UUID> statusId;
#Mock
Path<String> path;
#Mock
Expression expr;
#Mock
Predicate predicate;
#Mock
TypedQuery<Member> querymem;
#Mock
Root<Search> rSearchRootMock;
#InjectMocks
private SearchServiceImpl SearchService;
#Value("${query.limit}")
String queryLimit;
#Before
public void init() {
MockitoAnnotations.initMocks(SearchService);
SearchRootMock = mock(Root.class);
}
#Test
public void test_findby_criteria() {
hen(entityManager.getCriteriaBuilder()).thenReturn(criteriaBuilder); when(criteriaBuilder.createQuery(Search.class)).thenReturn(criteriaQuery);
when(criteriaQuery.from(Search.class)).thenReturn(SearchRootMock);
Path statusIdMock = mock(Path.class);
//when(Integer.parseInt(queryLimit)).thenReturn(1);
String status = "statusId";
Expression<String> doublePath = root.get(status);
when(root.get((status))).thenReturn((Path) doublePath);
when(criteriaBuilder.upper(root.<String>get(status))).thenReturn(expr);
when(criteriaBuilder.equal(expr,status.toUpperCase())).thenReturn(predicate);
when(root.get("statusId")).thenReturn(path);
when(this.SearchService.findByCriteria(SearchCriteriaDTO)).thenReturn(Searches);
here i am trying to mock the predicate but getting null point exception due to root.get("statusId").
please let me know how to mock it.
here are the issues
how to handle and mock the #Value("${query.limit}") where i am reading limit from application properties file.
getting null point exception in predicate line.
predicates.add(builder.and(repl.get("statusId").in(statusIds)));
not able to map the column name here for repl.get("statusId") where getting null.
please help me to solve this problem.Thanks
below is the error
java.lang.NumberFormatException: For input string: "${query.limit}"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at com.capturerx.cumulus4.replenishment.impl.ReplenishmentSearchServiceImplTest.test_findby_criteria_for_success(ReplenishmentSearchServiceImplTest.java:118)
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.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.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
getting java.lang.NullPointerException at line
query.select(replenishments).where(predicates.toArray(new Predicate[predicates.size()]));
I am throwing a ZuulRuntimeException and written a test case to validate it but it is throwing a different one.
Code:
public String extractCdsid(String accessToken) {
ObjectMapper objectMapper = new ObjectMapper();
String cdsid = "";
try {
String payload = JwtHelper.decode(accessToken).getClaims();
cdsid = objectMapper.readTree(payload).get("upn").textValue();
} catch (NullPointerException e) {
ZuulException ex = new ZuulException(
"Token does not contain upn. Please send a valid that contains upn(cdsid)", 401, "");
throw new ZuulRuntimeException(ex);
} }
Testcase:
#Test(expected = ZuulRuntimeException.class)
public void getPrincipalHeader_withAuthorizationHeaderNotContainUpn_returnsException(){
// mock
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("Authorization", "sendingtokenthatdoesnotcontainupn");
// run
tokenParser.getPrincipalHeader(req);
}
I am getting
java.lang.Exception: Unexpected exception, expected<com.netflix.zuul.exception.ZuulException> but was<java.lang.IllegalStateException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
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)
Caused by: java.lang.IllegalStateException: CounterFactory not initialized
at com.netflix.zuul.monitoring.CounterFactory.instance(CounterFactory.java:42)
at com.netflix.zuul.exception.ZuulException.incrementCounter(ZuulException.java:73)
at com.netflix.zuul.exception.ZuulException.<init>(ZuulException.java:54)
at com.cv.vadr.vadrgateway.util.TokenParser.extractCdsid(TokenParser.java:51)
at com.cv.vadr.vadrgateway.util.TokenParser.getPrincipalHeader(TokenParser.java:32)
at com.cv.vadr.vadrgateway.util.TokenParserTest.getPrincipalHeader_withAuthorizationHeaderNotContainUpn_returnsException(TokenParserTest.java:67)
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.ExpectException.evaluate(ExpectException.java:19)
... 16 more
I see the correct exception being thrown with message when I hit the service through postman
I had the same problem and for me adding
#Before
public void setUp() {
CounterFactory.initialize(new EmptyCounterFactory());
}
worked. Thanks to that I get rid of the java.lang.IllegalStateException: CounterFactory not initialized
I am trying to write test cases for an endpoint controller for the following controllers
#RestController
#RequestMapping("/agent/")
public class AgentRestController extends BaseRestController {
#RequestMapping(value = "/log/{revisionId}/", method = RequestMethod.PUT)
public ResponseEntity<?> log(#PathVariable("revisionId") String revisionId, #RequestBody LogMessage message) {
ConfigurationRevision cr = configurationRevisionRepository.findOne(revisionId);
BackupLog log = new BackupLog(message);
log.setRevision(cr);
backupLogRepository.save(log);
return new ResponseEntity<>(HttpStatus.CREATED);
}
#RequestMapping("/config")
#ResponseBody
public AgentConfig getConfiguration(HttpServletRequest request) {
AgentConfig cfg = getAgentConfigByIP(request.getRemoteAddr());
LogMessage log = new LogMessage();
log.level = LogLevel.INFO;
log.date = System.currentTimeMillis();
log.msg = "SYSTEM: Configuration retrieved by client";
// log the configuration retrieval
log(cfg.id, log);
return cfg;
}
}
I am trying to write Junit Test cases for these controllers
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = { Application.class })
#WebAppConfiguration
public class ApiControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
#Test
public void getConfigurationSuccess() throws Exception {
mockMvc.perform(get("/agent/config").accept(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful());
}
}
This is the stacktrace
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at backup.itests.ServiceTest.getConfigurationSuccess(ServiceTest.java:43)
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.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:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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:193)
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)
Caused by: java.lang.NullPointerException
at backup.restservice.BaseRestController.getAgentConfigByIP(BaseRestController.java:25)
at backup.restservice.AgentRestController.getConfiguration(AgentRestController.java:34)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
... 39 more
Can Someone help me in writing JUnit or JBehave testcases for the the given two controller and Expanding the test case for the controllers in AgenRestController. This would be a Great and a constructive help.
private WebApplicationContext webApplicationContext;
#Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
Just a shot in the dark here, but webApplicationContext is null, and not initialized. Perhaps before the this.mockMcx = ... you might insert the line:
webApplicationContext = new WebApplicationContext();