How to perform Unit Test using Java Mockito
I'm trying test this code using mockito, so need to mock the result as error and test the code. In this case, I've hardcoded the result as 1.
public class RetrieveData {
public int retrieveMetaData() {
int retries = 0;
int result = 0;
int MAX_RETRIES = 3;
while (retries++ < MAX_RETRIES) {
try {
result = 1;
} catch (Exception e) {
if(retries < MAX_RETRIES) {
System.out.println(" retries :" + retries );
} else {
throw e;
}
}
}
return result;
}
public static void main(String args) {
int result ;
RetrieveData obj = new RetrieveData();
result = obj.retrieveMetaData();
System.out.println(result);
}
}
Mockito:
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class TestretrieveMetaData {
@Test
public void test_retrieveMetaData() throws Exception {
RetrieveData resultObj = mock(RetrieveData.class);
// how to add the mock for the result.
}
}
java junit mockito
add a comment |
I'm trying test this code using mockito, so need to mock the result as error and test the code. In this case, I've hardcoded the result as 1.
public class RetrieveData {
public int retrieveMetaData() {
int retries = 0;
int result = 0;
int MAX_RETRIES = 3;
while (retries++ < MAX_RETRIES) {
try {
result = 1;
} catch (Exception e) {
if(retries < MAX_RETRIES) {
System.out.println(" retries :" + retries );
} else {
throw e;
}
}
}
return result;
}
public static void main(String args) {
int result ;
RetrieveData obj = new RetrieveData();
result = obj.retrieveMetaData();
System.out.println(result);
}
}
Mockito:
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class TestretrieveMetaData {
@Test
public void test_retrieveMetaData() throws Exception {
RetrieveData resultObj = mock(RetrieveData.class);
// how to add the mock for the result.
}
}
java junit mockito
1
Unrelated: read about java naming conventions. Class names go UpperCase, always. And the common practice is to name the test class for X.java ... simply XTest.java ... and not Testx.
– GhostCat
Nov 26 '18 at 11:32
1
Sinceresultis set to a primitive in the class/method under test, there is no way of mocking it. Also, it shouldn't be mocked. If it was set to the result of a method invocation to another class, you would mock this invocation.
– Tobb
Nov 26 '18 at 11:33
add a comment |
I'm trying test this code using mockito, so need to mock the result as error and test the code. In this case, I've hardcoded the result as 1.
public class RetrieveData {
public int retrieveMetaData() {
int retries = 0;
int result = 0;
int MAX_RETRIES = 3;
while (retries++ < MAX_RETRIES) {
try {
result = 1;
} catch (Exception e) {
if(retries < MAX_RETRIES) {
System.out.println(" retries :" + retries );
} else {
throw e;
}
}
}
return result;
}
public static void main(String args) {
int result ;
RetrieveData obj = new RetrieveData();
result = obj.retrieveMetaData();
System.out.println(result);
}
}
Mockito:
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class TestretrieveMetaData {
@Test
public void test_retrieveMetaData() throws Exception {
RetrieveData resultObj = mock(RetrieveData.class);
// how to add the mock for the result.
}
}
java junit mockito
I'm trying test this code using mockito, so need to mock the result as error and test the code. In this case, I've hardcoded the result as 1.
public class RetrieveData {
public int retrieveMetaData() {
int retries = 0;
int result = 0;
int MAX_RETRIES = 3;
while (retries++ < MAX_RETRIES) {
try {
result = 1;
} catch (Exception e) {
if(retries < MAX_RETRIES) {
System.out.println(" retries :" + retries );
} else {
throw e;
}
}
}
return result;
}
public static void main(String args) {
int result ;
RetrieveData obj = new RetrieveData();
result = obj.retrieveMetaData();
System.out.println(result);
}
}
Mockito:
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class TestretrieveMetaData {
@Test
public void test_retrieveMetaData() throws Exception {
RetrieveData resultObj = mock(RetrieveData.class);
// how to add the mock for the result.
}
}
java junit mockito
java junit mockito
edited Nov 26 '18 at 11:34
Sathish G
asked Nov 26 '18 at 11:27
Sathish GSathish G
215
215
1
Unrelated: read about java naming conventions. Class names go UpperCase, always. And the common practice is to name the test class for X.java ... simply XTest.java ... and not Testx.
– GhostCat
Nov 26 '18 at 11:32
1
Sinceresultis set to a primitive in the class/method under test, there is no way of mocking it. Also, it shouldn't be mocked. If it was set to the result of a method invocation to another class, you would mock this invocation.
– Tobb
Nov 26 '18 at 11:33
add a comment |
1
Unrelated: read about java naming conventions. Class names go UpperCase, always. And the common practice is to name the test class for X.java ... simply XTest.java ... and not Testx.
– GhostCat
Nov 26 '18 at 11:32
1
Sinceresultis set to a primitive in the class/method under test, there is no way of mocking it. Also, it shouldn't be mocked. If it was set to the result of a method invocation to another class, you would mock this invocation.
– Tobb
Nov 26 '18 at 11:33
1
1
Unrelated: read about java naming conventions. Class names go UpperCase, always. And the common practice is to name the test class for X.java ... simply XTest.java ... and not Testx.
– GhostCat
Nov 26 '18 at 11:32
Unrelated: read about java naming conventions. Class names go UpperCase, always. And the common practice is to name the test class for X.java ... simply XTest.java ... and not Testx.
– GhostCat
Nov 26 '18 at 11:32
1
1
Since
result is set to a primitive in the class/method under test, there is no way of mocking it. Also, it shouldn't be mocked. If it was set to the result of a method invocation to another class, you would mock this invocation.– Tobb
Nov 26 '18 at 11:33
Since
result is set to a primitive in the class/method under test, there is no way of mocking it. Also, it shouldn't be mocked. If it was set to the result of a method invocation to another class, you would mock this invocation.– Tobb
Nov 26 '18 at 11:33
add a comment |
1 Answer
1
active
oldest
votes
First of all, you have to understand what you intend to do!
You see, you either mock a class X ... because an instance of X is used in some class Y, and you intend to test Y. Or you intend to test class X, but then you shouldn't mock instances of X! Either you test X, or you use X for testing something else.
Assuming that you want to mock an instance of your class RetrieveData, you simply do:
RetrieveData resultObj = Mockito.mock(RetrieveData.class);
Mockito.when(resultObj.retrieveMetaData()).thenReturn(42);
So, to align with that comment by Tobb: you can't "mock" that result field alone. If at all, you can mock complete instances of your class. But as said: that only makes sense when you use that instance within another class you intend to test.
Long story short: as said, the real issue is that you are trying to use concepts that you simply do not understand (no judgement here). My recommendation: start by reading a good tutorial on Mockito. Then spent a lot of time thinking "how can I write code that I can test in reasonable ways". You are trying to start with step 10, but that won't work, because you can only do that when you made steps 1 to 9 before, and understand what they are about.
And yes, you can use a Mockito spy when you want to "partial mocking". Using that, you can test parts of X, whilst also "mocking out" other parts of X. But that is really an advanced feature, and most likely not the topic you should study first.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53480126%2fhow-to-perform-unit-test-using-java-mockito%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
First of all, you have to understand what you intend to do!
You see, you either mock a class X ... because an instance of X is used in some class Y, and you intend to test Y. Or you intend to test class X, but then you shouldn't mock instances of X! Either you test X, or you use X for testing something else.
Assuming that you want to mock an instance of your class RetrieveData, you simply do:
RetrieveData resultObj = Mockito.mock(RetrieveData.class);
Mockito.when(resultObj.retrieveMetaData()).thenReturn(42);
So, to align with that comment by Tobb: you can't "mock" that result field alone. If at all, you can mock complete instances of your class. But as said: that only makes sense when you use that instance within another class you intend to test.
Long story short: as said, the real issue is that you are trying to use concepts that you simply do not understand (no judgement here). My recommendation: start by reading a good tutorial on Mockito. Then spent a lot of time thinking "how can I write code that I can test in reasonable ways". You are trying to start with step 10, but that won't work, because you can only do that when you made steps 1 to 9 before, and understand what they are about.
And yes, you can use a Mockito spy when you want to "partial mocking". Using that, you can test parts of X, whilst also "mocking out" other parts of X. But that is really an advanced feature, and most likely not the topic you should study first.
add a comment |
First of all, you have to understand what you intend to do!
You see, you either mock a class X ... because an instance of X is used in some class Y, and you intend to test Y. Or you intend to test class X, but then you shouldn't mock instances of X! Either you test X, or you use X for testing something else.
Assuming that you want to mock an instance of your class RetrieveData, you simply do:
RetrieveData resultObj = Mockito.mock(RetrieveData.class);
Mockito.when(resultObj.retrieveMetaData()).thenReturn(42);
So, to align with that comment by Tobb: you can't "mock" that result field alone. If at all, you can mock complete instances of your class. But as said: that only makes sense when you use that instance within another class you intend to test.
Long story short: as said, the real issue is that you are trying to use concepts that you simply do not understand (no judgement here). My recommendation: start by reading a good tutorial on Mockito. Then spent a lot of time thinking "how can I write code that I can test in reasonable ways". You are trying to start with step 10, but that won't work, because you can only do that when you made steps 1 to 9 before, and understand what they are about.
And yes, you can use a Mockito spy when you want to "partial mocking". Using that, you can test parts of X, whilst also "mocking out" other parts of X. But that is really an advanced feature, and most likely not the topic you should study first.
add a comment |
First of all, you have to understand what you intend to do!
You see, you either mock a class X ... because an instance of X is used in some class Y, and you intend to test Y. Or you intend to test class X, but then you shouldn't mock instances of X! Either you test X, or you use X for testing something else.
Assuming that you want to mock an instance of your class RetrieveData, you simply do:
RetrieveData resultObj = Mockito.mock(RetrieveData.class);
Mockito.when(resultObj.retrieveMetaData()).thenReturn(42);
So, to align with that comment by Tobb: you can't "mock" that result field alone. If at all, you can mock complete instances of your class. But as said: that only makes sense when you use that instance within another class you intend to test.
Long story short: as said, the real issue is that you are trying to use concepts that you simply do not understand (no judgement here). My recommendation: start by reading a good tutorial on Mockito. Then spent a lot of time thinking "how can I write code that I can test in reasonable ways". You are trying to start with step 10, but that won't work, because you can only do that when you made steps 1 to 9 before, and understand what they are about.
And yes, you can use a Mockito spy when you want to "partial mocking". Using that, you can test parts of X, whilst also "mocking out" other parts of X. But that is really an advanced feature, and most likely not the topic you should study first.
First of all, you have to understand what you intend to do!
You see, you either mock a class X ... because an instance of X is used in some class Y, and you intend to test Y. Or you intend to test class X, but then you shouldn't mock instances of X! Either you test X, or you use X for testing something else.
Assuming that you want to mock an instance of your class RetrieveData, you simply do:
RetrieveData resultObj = Mockito.mock(RetrieveData.class);
Mockito.when(resultObj.retrieveMetaData()).thenReturn(42);
So, to align with that comment by Tobb: you can't "mock" that result field alone. If at all, you can mock complete instances of your class. But as said: that only makes sense when you use that instance within another class you intend to test.
Long story short: as said, the real issue is that you are trying to use concepts that you simply do not understand (no judgement here). My recommendation: start by reading a good tutorial on Mockito. Then spent a lot of time thinking "how can I write code that I can test in reasonable ways". You are trying to start with step 10, but that won't work, because you can only do that when you made steps 1 to 9 before, and understand what they are about.
And yes, you can use a Mockito spy when you want to "partial mocking". Using that, you can test parts of X, whilst also "mocking out" other parts of X. But that is really an advanced feature, and most likely not the topic you should study first.
edited Nov 28 '18 at 19:42
Loïc Le Doyen
384110
384110
answered Nov 26 '18 at 11:35
GhostCatGhostCat
1
1
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53480126%2fhow-to-perform-unit-test-using-java-mockito%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Unrelated: read about java naming conventions. Class names go UpperCase, always. And the common practice is to name the test class for X.java ... simply XTest.java ... and not Testx.
– GhostCat
Nov 26 '18 at 11:32
1
Since
resultis set to a primitive in the class/method under test, there is no way of mocking it. Also, it shouldn't be mocked. If it was set to the result of a method invocation to another class, you would mock this invocation.– Tobb
Nov 26 '18 at 11:33