Hi So I'm new to Junit and Mockito, so please bare with some misconception/mistakes that Ive made. I have a springbott service that I wanted to test and I want to mock a method call that is being made in one of the methods that I am testing but It will not work for some reason. I used both when(xxx.method(anyArgs)).return(someData) as well as doReturn(someData).when(xxx).method(anyArgs); But I still get the same type of error: InvalidUseOfMatchersException. I mock the service layer but I can not figure out what causes the issue.
The Exact Stack Trace:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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)
My Service Layer Code:
// imports here
#Service
#AllArgsConstructor
public class EventServiceImpl implements EventService {
private EventModelRepo eventModelRepo;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// methods that dont matter
public int createAPost(EventDetails eventDetails) {
//Some where here the isOwner(STRING) is called
}
public static void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
public boolean isOwner(String Owner) {
try {
getRequest("http://localhost:9024/login/isAuth?Username=" + Owner);
} catch (HttpResponseException e) {
System.out.println("Error: " + e.getContent());
return false;
} catch (IOException e) {
System.out.println("Could Not Connect To Site/Make Said Request. \nAre You In Testing? \nIf So This Is Ok.");
}
return true;
}
}
And here is my Junit:
//imports
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
// mocking the HTTP Call in isOwner()
HttpTransport transport = new MockHttpTransport();
HttpRequest request = null;
try {
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpResponse response = request.execute();
} catch (IOException e) {
e.printStackTrace();
}
EventDetails eventDetails = new EventDetails("username1", "resturant", "idk", "location.", ".com",
"no", "no p", "spring", "fair", "tes");
//If Owner Isn't Validate As Owner/Signed In
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
//doReturn(false).when(eventServiceImpl).isOwner(anyString());
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
So turns out one of the commentors on my post was correct. You can not mock a call from a #InjectMocks. But if you want to you need to have another annotation added to it. That annotation being #Spy. This annotation should be added in the test class, above the #InjectMocks.
More can be found here
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#Spy
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
Related
This function tries to retrieve the topic of the GitHub repository name using the GitHub API: https://api.github.com/repos/flutter/flutter/topics
public List<String> getTopics(SearchRepository searchRepository){
GitHubRequest request = new GitHubRequest();
List<String> topic_list = new ArrayList<>();
try {
String url = searchRepository.getUrl().split("//")[1].split("github.com")[1];
request.setUri("/repos"+ url + "/topics");
String result = new BufferedReader(new InputStreamReader(gitHubClient.getStream(request)))
.lines().collect(Collectors.joining("\n"));
JSONObject jsonObject = new JSONObject(result);
topic_list = Arrays.stream(jsonObject.get("names").toString().replace("[", "").replace("]", "").split(",")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return topic_list;
}
The url returned before string to list conversion is :https://github.com/repouser/reponame
SearchRepository is the v2 model class of Repository from the package:
SearchRepositroy
As per the earlier suggestions from this wonderful community answers (though the question is now edited, it remains yet relevant) I created the mock test to test the above function as below:
#Test
public void getTopicsTest() throws IOException{
SearchRepository mocksearchRepository = mock(SearchRepository.class);
GitHubClient mockClient = mock(GitHubClient.class);
GitHubRequest mockRequest = mock(GitHubRequest.class);
when(mocksearchRepository.getUrl()).thenReturn("https://github.com/mockuser/mockrepo");
when(mocksearchRepository.getName()).thenReturn("mockrepo");
when(mocksearchRepository.getOwner()).thenReturn("mockuser");
//when(mockRequest.setUri((String) any())).thenReturn(mockRequest.setUri("/repo/mockuser/mockrepo/topics"));
//The format of the return form is: https://github.com/CyC2018/CS-Notes
when(mockClient.getStream(any())).thenReturn(topicInputStream());
//SearchRepository querySearch = new SearchRepository("mockuser","mockrepo");
List<String> topics = githubServiceMock.getTopics(mocksearchRepository);
System.out.println(topics);
}
private InputStream topicInputStream() {
String mockTopics = "{" +
"topic1\": [" +
"topic2\"," +
"topic3\"," +
"skia" +
"]" +
"}";
InputStream stream = new ByteArrayInputStream(mockTopics.getBytes(StandardCharsets.UTF_8));
System.out.println(stream);
return stream;
}
However, I get the 404 internal server error Exception due to the request.setUri(Uri(String)) in the function. Please suggest where I am going wrong.
Test services.GithubServiceTest.getTopicsTest started
java.io.ByteArrayInputStream#6ed99482
org.eclipse.egit.github.core.client.RequestException: Not Found (404)
| => rat org.eclipse.egit.github.core.client.GitHubClient.createException(GitHubClient.java:552)
at org.eclipse.egit.github.core.client.GitHubClient.getResponseStream(GitHubClient.java:701)
at org.eclipse.egit.github.core.client.GitHubClient.getStream(GitHubClient.java:667)
at services.GithubService.getTopics(GithubService.java:231)
at services.GithubServiceTest.getTopicsTest(GithubServiceTest.java:222)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at com.novocode.junit.JUnitRunner$1.execute(JUnitRunner.java:132)
at sbt.ForkMain$Run.lambda$runTest$1(ForkMain.java:413)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
[]
[info] Test services.GithubServiceTest.getIssueWordLevelStatisticsTest started
[info] Test services.GithubServiceTest.getRepositoriesByTopicTest started
[info] Test services.GithubServiceTest.getUserDetailsTest started
[info] Test services.GithubServiceTest.getRepositoryDetailsTest started
[info] Test run finished: 0 failed, 0 ignored, 5 total, 1.122s
[error] Failed: Total 10, Failed 1, Errors 0, Passed 9
[error] Failed tests:
[error] controllers.GithubControllerTest
[error] (Test / test) sbt.TestsFailedException: Tests unsuccessful
You can mock repositoryService and gitHubClient to test various scenarios.
You can provide a package-level setter for these fields. It is a great idea to annotate it with Guava VisibleForTesting annotation.
Then you need to set mocks before the actual test on the instance.
Pseudocode for mocking
// First, we mock repository so we can return it from service
Repository repositoryMock = mock(Repository.class);
when(repository.getUrl()).thenReturn("https://...."); // You can return a URL or String, according to the mocked method's return type
// Then, we mock RepositoryService as well
RepositoryService repositoryServiceMock = mock(RepositoryService.class);
when(repositoryServiceMock.getRepository(anyString(), anyString()).thenReturn(repositoryMock);
// We mock gitHubService similarly
...
// After setting mock on the instance, we call the method and see if the results are expected
List<String> topics = getTopics("...", "...");
assertEquals(topics, ...);
// You can also assert interaction related things
verify(repositoryService).getRepository("a", "b"); // This is OK only if the service is called with "a" and "b" arguments
First, you need to inject the mock object (repositoryService,gitHubClient) to your function.
If you use spring/spring boot, you can consider to use #Mock and #MockBean annotation.
to mock the necessary bean.
The below code to create mock object manually.
RepositoryService fakeRs = Mockito.mock(RepositoryService.class);
GitHubClient fakeGHC = Mockito.mock(GitHubClient.class);
You also can use setter method to set mock object.
setRepositoryService(fakeRs);
setGitHubClient(fakeGHC);
The other way is using reflection utility to set private object.
ReflectionTestUtils.setField(yourService, "repositoryService", fakeRs);
ReflectionTestUtils.setField(yourService, "gitHubClient", fakeGHC);
After finish ingesting the mock object, you can write an test with expected behavior/data from mock object.
#Test
public void testGetTopics(){
// init mock object code in case setter/getter/reflection utils
Repository expectedRepository = createExampleRepository();
Mockito.when(repositoryService.getRepository(Mockito.anyString(),Mockito.anyString())
.thenReturn(expectedRepository);
// continue to fake gitHubClient with your expected data/ exceptions...
//call your method
List<?> data = yourService.getTopic("user","data");
Assertions.assertTrue(data!=null);
// you can write few assertion base on your fake datas
}
PS: Don't copy/paste the code, you will get compile errors. I am not using editor tool.
How do I resolve this NullPointerException ?
A little background , I am developing a Spring based Project and using HibernateTemlate in DAO layer to do all database related operations.
here is the snippet of code which i have extracted out of my test class which is throwing NullPointerException.
try {
List<Object[]> list = (List<Object[]>) ht.find("select uomId,uomModel from in.nit.model.Uom");
System.out.println(list);
}catch(NullPointerException e) {
e.printStackTrace();
}
And this is the stacktrace of the exception on the console.
```
java.lang.NullPointerException
at in.nit.dao.impl.UomDaoImplTest.test(UomDaoImplTest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
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:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
```
Here is my model class
```
#Entity
#Table(name="uomtab")
public class Uom {
#Id #GeneratedValue #Column(name="umid") private Integer uomId;
#Column(name="utype") private String uomType;
#Column(name="umodel") private String uomModel;
#Column(name="udesc") private String uomDesc;
public Uom() {
super();
}
public Uom(Integer uomId) {
this.uomId = uomId;
}
public Integer getUomId() {
return uomId;
}
public void setUomId(Integer uomId) {
this.uomId = uomId;
}
public String getUomType() {
return uomType;
}
public void setUomType(String uomType) {
this.uomType = uomType;
}
public String getUomModel() {
return uomModel;
}
public void setUomModel(String uomModel) {
this.uomModel = uomModel;
}
public String getUomDesc() {
return uomDesc;
}
public void setUomDesc(String uomDesc) {
this.uomDesc = uomDesc;
}
#Override
public String toString() {
return "Uom [uomId=" + uomId + ", uomType=" + uomType + ", uomModel=" + uomModel + ",
uomDesc=" + uomDesc + "]";
}
}
```
Also even though the find(String Query) method is deprecated,I have extensively used it in other dao classes of my project which works smooth and fine.
What could be the possible reasons for this exception blowing up my code?
You shouldn't catch that NullPointerException
What is line 28 in your code?
Did you try and debug the line? If it is the ht.find line, the only thing that makes sense is that your HibernateTemplate is null and has not been set correctly.
your error is in class "UomDaoImplTest". That has no relation with Hibernate Template.
can you post your test class.
I am getting the error below:
java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.json.webtoken.JsonWebSignature$Parser.parse(JsonWebSignature.java:599)
at com.google.firebase.auth.FirebaseToken.parse(FirebaseToken.java:44)
at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:456)
at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:449)
at com.google.firebase.internal.CallableOperation.call(CallableOperation.java:36)
at com.google.firebase.auth.FirebaseAuth.verifyIdToken(FirebaseAuth.java:413)
at d.d.pamper.test.ApplicationTest.testFire2(ApplicationTest.java:46)
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.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 realize the stack is not very helpful. I've debugged inside the Admin SDK. It reads my service json correctly, the FirebaseAuth.getInstance() is not null, I can see my project id get set correctly.
This is how I'm initializing:
if(FirebaseApp.getApps().size() > 0) {
System.out.println("initialized already ");
return;
}
FirebaseOptions options = null;
try {
System.out.println("try initializing");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(gservicesConfig.getInputStream()))
.setDatabaseUrl("https://pamperanywhere.firebaseio.com")
.build();
} catch (IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
return;
This is how I'm testing my token:
#Test
public void testFire2() {
String idToken = "REFRESH TOKEN FROM FIREBASE";
if(!StringUtils.isEmpty(idToken)) {
FirebaseToken firebaseToken = null;
if(FirebaseAuth.getInstance() == null) {
System.out.println("FirebaseAuth.getInstance() == null");
}
try {
firebaseToken = FirebaseAuth.getInstance().verifyIdToken(idToken, true);
} catch (IllegalArgumentException e) {
System.out.println("exception+IllegalArgumentException");
e.printStackTrace();
} catch (FirebaseAuthException e) {
System.out.println("exception+FirebaseAuthException");
e.printStackTrace();
}
if (firebaseToken == null) {
System.out.println("firebaseToken == null");
}
}
}
I'm not sure why its throwing IllegalArgumentException. I'm able to login to the application fine (front end), I see my refresh token (front end) but on the Admin side its giving me this issue. I am sure I'm passing the correct token because I can login and see the token (front end).
Maven is:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.2.0</version>
</dependency>
Thank you for your help.
An ID token should be a valid JWT with 3 segments (separated by dots). Refresh tokens are certainly not that. Therefore the underlying token parser is failing with the above assertion error. Here's the relevant bit of code from the Google API client. Basically it cannot find any dots in the given token string.
public JsonWebSignature parse(String tokenString) throws IOException {
// split on the dots
int firstDot = tokenString.indexOf('.');
Preconditions.checkArgument(firstDot != -1);
...
There's a listener:
firebase.auth().onIdTokenChanged((user: firebase.User) => {
console.log("onIdTokenChanged");
if(user && user.uid) {
user.getIdToken(false)
.then((data: any) => {
console.log("data: ", data);
this.idToken = data;
});
}
});
this gets invoked every one hour. I thought I had to implement this logic myself!
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onIdTokenChanged
From official; above is from Ionic2/Angular2, I have that in a dataServiceProvider 's constructor.
firebase.auth().onIdTokenChanged(function(user) {
if (user) {
// User is signed in or token was refreshed.
}
});
I am new to JUNIT testing but tried a lot to test the class UserProfileService. Please help or suggest possible errors I am doing:
#Path("/update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateProfile(final PartyProfile partyProfile) {
final ProxyResponse response = new ProxyResponse();
try {
final boolean isUpdated = partyProfileDao.updateProfile(partyProfile);
if (isUpdated) {
LOGGER.info("update Request completed successfully");
setSuccessResponse(response, "Request completed successfully");
try{
final String trailId = partyProfileDao.fetchPartyTrial(partyProfile.getPartyId());
activityPush(trailId, partyProfile.getPartyId());
}catch(Exception ex){
ex.printStackTrace();
LOGGER.error("Exception while triggering segmentation++");
}
} else {
LOGGER.info("Unable to update profile");
setErrorResponse(response, "PRFUPDT500", "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
} catch (Exception exc) {
LOGGER.error("Unable to update profile:" + exc.getMessage());
setInternalErrorResponse(exc, response, "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
return Response.ok(response).build();
}
I have written following JUNIT test:
public class PartyProfileServiceTest {
private PartyProfileDAO partyDAO;
private PartyProfileService partyService;
#Before
public void setUp() throws Exception {
partyDAO = EasyMock.createMock(PartyProfileDAO.class);
partyService = EasyMock.createMock(PartyProfileService.class);
partyService.setUserProfileDAO(partyDAO);
}
#Test
public void testUpdateValidProfile() throws Exception {
System.out.println("inside junit");
PartyProfile partyProfile = new PartyProfile();
partyProfile.setFirstName("adsfsdfg");
partyProfile.setAddress("adressabc");
partyProfile.setPartyId("dfdf");
partyProfile.getSalutation();
partyProfile.setMiddleName("asfsaf");
partyProfile.setLastName("easdsddff");
partyProfile.setNickName("srb");
partyProfile.setGender("m");
partyProfile.setUpdateDate("sdd");
partyProfile.setEducation("srg");
partyProfile.setInsurance("sg");
partyProfile.setState("sdfg");
partyProfile.setSiteId("fdg");
partyProfile.setRandomNo("feddg");
partyProfile.setPartyId("56666");
EasyMock.expect(partyDAO.updateProfile(partyProfile)).andReturn(true);
EasyMock.expect(partyDAO.fetchPartyTrial("validPartyId")).andReturn("pass");
EasyMock.replay(partyDAO);
EasyMock.expect(partyService.activityPush("pass", "validPartyId")).andReturn(true);
EasyMock.replay(partyService);
Response response = partyService.updateProfile(partyProfile);
ProxyResponse proxyResponse = (ProxyResponse) response.getEntity();
Assert.assertSame("Unable to update profile", proxyResponse.getData().get("message"));
}
}
Error:
java.lang.AssertionError:
Unexpected method call PartyProfileService.updateProfile(com.cts.vcoach.proxy.model.PartyProfile#11e170c):
PartyProfileService.setUserProfileDAO(EasyMock for class com.cts.vcoach.proxy.dao.PartyProfileDAO): expected: 1, actual: 0
PartyProfileService.activityPush("pass", "validPartyId"): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at com.cts.vcoach.proxy.service.rest.PartyProfileService$$EnhancerByCGLIB$$46a1112f.updateProfile(<generated>)
at com.cts.vcoach.proxy.service.rest.PartyProfileServiceTest.testUpdateValidProfile(PartyProfileServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
You're trying to test the class PartyProfileService. So you should create an instance of this class, and call its methods in your test. But that's not what you're doing. You're creating a mock instance of this class:
partyService = EasyMock.createMock(PartyProfileService.class);
Replace this line by
partyService = new PartyProfileService();
If you need to partially mock the service, i.e. mock the method activityPush(), but not the other ethods, then see the documentation for how to do that:
ToMock mock = createMockBuilder(ToMock.class)
.addMockedMethod("mockedMethod")
.createMock();
I would like to mock the make a JUnit test of the following method toXml:
void toXml(Object obj){
ByteArrayOutputStream out = null;
try{
JAXBContext ctx = getContext(obj.getClass());
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setAttachmentMarshaller(new AttachmentMarshallerImpl());
out = new ByteArrayOutputStream();
marshaller.marshal( obj, out );
}catch( JAXBException e ){
throw new RuntimeException("Problem in parsing", e);
}
}
I have tried the following:
#Test
public void testToXml() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
SystemPointDto systemPointDto = new SystemPointDto();
verify((marshaller), atLeast(1)).marshal(systemPointDto, out);
}
However I am getting a NullPointerException when I run the test. I am a newbie in testing probably the answer is very easy. Could you please advice? Thanks in advance.
EDIT:
The mocking code as asked in the comments is:
#Mock
AttachmentMarshallerImpl attachmentMarshaller;
#InjectMocks
Marshaller marshaller;
And this is the stack trace:
initMocks(TestingIfTheMarshalGetsCalledWithoutExceptionTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Caused by: org.mockito.exceptions.base.MockitoException: the type 'Marshaller' is an interface.
... 32 more
In your Method you get the Marshaller from a JAXBContext. To use your mock Marshaller, your need a JAXBContext that returns the mock when createMarshaller is called.
assuming the following class under test:
public class XmlMarshaller {
private JAXBContextFactory contextFactory;
public XmlMarshaller(JAXBContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
private JAXBContext getContext(Class<?> type) {
return contextFactory.get(type);
}
public void toXml(Object obj){
// ... your code
}
}
your test setup would need to look like this:
public class XmlMarshallerTest {
#Mock
JAXBContext ctx;
#Mock
Marshaller marshaller;
#Mock
JAXBContextFactory factory;
#InjectMocks
XmlMarshaller classUnderTest;
#Before
public void setup() {
MockitoAnnotations.initMocks(this); // creates mocks and injects the as needed into the classUnderTest
when(ctx.createMarshaller()).thenReturn(marshaller);
}
#Test
public void toXmlCallsJAXBMarshaller() {
when(factory.get(SystemPointDto.class)).thenReturn(ctx);
SystemPointDto systemPointDto = new SystemPointDto();
classUnderTest.toXml(systemPointDto);
verify(marshaller).marshal(eq(systemPointDto), any(ByteArrayOutputStream.class));
}
}