how to do junit test for data base insertion using hibernateHow do you assert that a certain exception is thrown in JUnit 4 tests?JUnit test for System.out.println()JUnit test of the same objecthow to select value from database using hibernate?Hibernate update table B after table A is updatedXpages - Get number of active sessions (Lotus Domino 8.5.2)H2 DB — Hibernate Example — Could not parse mapping document from resource@Formula pattern in hibernateHow to give foreign key in HibernateMappingJackson2HttpMessageConverter Can not find a (Map) Key deserializer for type
Is the U.S. Code copyrighted by the Government?
Delivering sarcasm
Intuition of generalized eigenvector.
Removing files under particular conditions (number of files, file age)
How much character growth crosses the line into breaking the character
On a tidally locked planet, would time be quantized?
Lowest total scrabble score
What was the exact wording from Ivanhoe of this advice on how to free yourself from slavery?
Why do we read the Megillah by night and by day?
I am looking for the correct translation of love for the phrase "in this sign love"
Open a doc from terminal, but not by its name
Is it possible to put a rectangle as background in the author section?
Why is so much work done on numerical verification of the Riemann Hypothesis?
A social experiment. What is the worst that can happen?
Does a 'pending' US visa application constitute a denial?
Has any country ever had 2 former presidents in jail simultaneously?
Request info on 12/48v PSU
Calculating Wattage for Resistor in High Frequency Application?
Is it possible to have a strip of cold climate in the middle of a planet?
Offered money to buy a house, seller is asking for more to cover gap between their listing and mortgage owed
Why is it that I can sometimes guess the next note?
Freedom of speech and where it applies
Melting point of aspirin, contradicting sources
Why electric field inside a cavity of a non-conducting sphere not zero?
how to do junit test for data base insertion using hibernate
How do you assert that a certain exception is thrown in JUnit 4 tests?JUnit test for System.out.println()JUnit test of the same objecthow to select value from database using hibernate?Hibernate update table B after table A is updatedXpages - Get number of active sessions (Lotus Domino 8.5.2)H2 DB — Hibernate Example — Could not parse mapping document from resource@Formula pattern in hibernateHow to give foreign key in HibernateMappingJackson2HttpMessageConverter Can not find a (Map) Key deserializer for type
I was trying to do j-unit test for project which insert values into database using hibernate classes. The program is creating tables and inserting values into database. but i am not able to do the j-unit part for the test?
I have attached the java table, but the value that i inserting using the test file is not display when i debugged it?
Sample.java
@Entity
public class Sample
@Id
private int sid;
private String name;
public void set_sid(int sid)
this.sid=sid;
public void set_name(String name)
this.name=name;
public int get_sid()
return sid;
public String get_name()
return name;
SampleInsert.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleInsert
private Sample s;
private static SessionFactory sf;
public void insert()
sf = new Configuration().configure(new File("C:/Users/ns068002/eclipse-workspace/JAXRS-HelloWorld1/src/main/java/com/javacodegeeks/enterprise/rest/jersey/hibernate.cfg.xml")).buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Sample s=(Sample) session.get(Sample.class, 1);
System.out.println(s+"2");
System.out.println(s.get_name());
session.getTransaction().commit();
SampleInsertTest.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleTest
Session session;
SampleInsert st;
@Before
public void setUp()
session=mock(Session.class);
st=new SampleInsert();
@Test
public void test()
Sample s=new Sample();
s.set_sid(1);
s.set_name("gopal");
Mockito.when(session.get(Sample.class,1)).thenReturn(s);
System.out.println(s+"1");
st.insert();
java hibernate
New contributor
add a comment |
I was trying to do j-unit test for project which insert values into database using hibernate classes. The program is creating tables and inserting values into database. but i am not able to do the j-unit part for the test?
I have attached the java table, but the value that i inserting using the test file is not display when i debugged it?
Sample.java
@Entity
public class Sample
@Id
private int sid;
private String name;
public void set_sid(int sid)
this.sid=sid;
public void set_name(String name)
this.name=name;
public int get_sid()
return sid;
public String get_name()
return name;
SampleInsert.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleInsert
private Sample s;
private static SessionFactory sf;
public void insert()
sf = new Configuration().configure(new File("C:/Users/ns068002/eclipse-workspace/JAXRS-HelloWorld1/src/main/java/com/javacodegeeks/enterprise/rest/jersey/hibernate.cfg.xml")).buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Sample s=(Sample) session.get(Sample.class, 1);
System.out.println(s+"2");
System.out.println(s.get_name());
session.getTransaction().commit();
SampleInsertTest.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleTest
Session session;
SampleInsert st;
@Before
public void setUp()
session=mock(Session.class);
st=new SampleInsert();
@Test
public void test()
Sample s=new Sample();
s.set_sid(1);
s.set_name("gopal");
Mockito.when(session.get(Sample.class,1)).thenReturn(s);
System.out.println(s+"1");
st.insert();
java hibernate
New contributor
In theory you shouldn't need to test that hibernate is inserting data; it is probably more effective for you to test that your interface to hibernate is called correctly. A quick google search shows lots of interest in this and at least one tutorial such as: dzone.com/articles/testing-databases-junit-and
– Gavin
Mar 20 at 11:26
Thank you for replying. But i need to check whether how much code coverage is there. so i need to use junit testing and mockito framework. @Gavin
– Gauranga
Mar 20 at 11:35
You're welcome :) You don't "have" to use Mockito, you can write your own mocks and stubs, Mockito is not a precondition of code coverage. While 100% code coverage can be consider a laudable goal, it is not always an indication of a well tested code base. You should test the bits of code you (or your team) own.
– Gavin
Mar 20 at 11:43
But how to do junit test for the above class for SampleInsert.java. Just for information. Because i was trying to do junit using mockito but i wasnot able to do it.@Gavin
– Gauranga
Mar 21 at 4:51
add a comment |
I was trying to do j-unit test for project which insert values into database using hibernate classes. The program is creating tables and inserting values into database. but i am not able to do the j-unit part for the test?
I have attached the java table, but the value that i inserting using the test file is not display when i debugged it?
Sample.java
@Entity
public class Sample
@Id
private int sid;
private String name;
public void set_sid(int sid)
this.sid=sid;
public void set_name(String name)
this.name=name;
public int get_sid()
return sid;
public String get_name()
return name;
SampleInsert.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleInsert
private Sample s;
private static SessionFactory sf;
public void insert()
sf = new Configuration().configure(new File("C:/Users/ns068002/eclipse-workspace/JAXRS-HelloWorld1/src/main/java/com/javacodegeeks/enterprise/rest/jersey/hibernate.cfg.xml")).buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Sample s=(Sample) session.get(Sample.class, 1);
System.out.println(s+"2");
System.out.println(s.get_name());
session.getTransaction().commit();
SampleInsertTest.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleTest
Session session;
SampleInsert st;
@Before
public void setUp()
session=mock(Session.class);
st=new SampleInsert();
@Test
public void test()
Sample s=new Sample();
s.set_sid(1);
s.set_name("gopal");
Mockito.when(session.get(Sample.class,1)).thenReturn(s);
System.out.println(s+"1");
st.insert();
java hibernate
New contributor
I was trying to do j-unit test for project which insert values into database using hibernate classes. The program is creating tables and inserting values into database. but i am not able to do the j-unit part for the test?
I have attached the java table, but the value that i inserting using the test file is not display when i debugged it?
Sample.java
@Entity
public class Sample
@Id
private int sid;
private String name;
public void set_sid(int sid)
this.sid=sid;
public void set_name(String name)
this.name=name;
public int get_sid()
return sid;
public String get_name()
return name;
SampleInsert.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleInsert
private Sample s;
private static SessionFactory sf;
public void insert()
sf = new Configuration().configure(new File("C:/Users/ns068002/eclipse-workspace/JAXRS-HelloWorld1/src/main/java/com/javacodegeeks/enterprise/rest/jersey/hibernate.cfg.xml")).buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Sample s=(Sample) session.get(Sample.class, 1);
System.out.println(s+"2");
System.out.println(s.get_name());
session.getTransaction().commit();
SampleInsertTest.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleTest
Session session;
SampleInsert st;
@Before
public void setUp()
session=mock(Session.class);
st=new SampleInsert();
@Test
public void test()
Sample s=new Sample();
s.set_sid(1);
s.set_name("gopal");
Mockito.when(session.get(Sample.class,1)).thenReturn(s);
System.out.println(s+"1");
st.insert();
Sample.java
@Entity
public class Sample
@Id
private int sid;
private String name;
public void set_sid(int sid)
this.sid=sid;
public void set_name(String name)
this.name=name;
public int get_sid()
return sid;
public String get_name()
return name;
SampleInsert.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleInsert
private Sample s;
private static SessionFactory sf;
public void insert()
sf = new Configuration().configure(new File("C:/Users/ns068002/eclipse-workspace/JAXRS-HelloWorld1/src/main/java/com/javacodegeeks/enterprise/rest/jersey/hibernate.cfg.xml")).buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Sample s=(Sample) session.get(Sample.class, 1);
System.out.println(s+"2");
System.out.println(s.get_name());
session.getTransaction().commit();
SampleInsertTest.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleTest
Session session;
SampleInsert st;
@Before
public void setUp()
session=mock(Session.class);
st=new SampleInsert();
@Test
public void test()
Sample s=new Sample();
s.set_sid(1);
s.set_name("gopal");
Mockito.when(session.get(Sample.class,1)).thenReturn(s);
System.out.println(s+"1");
st.insert();
Sample.java
@Entity
public class Sample
@Id
private int sid;
private String name;
public void set_sid(int sid)
this.sid=sid;
public void set_name(String name)
this.name=name;
public int get_sid()
return sid;
public String get_name()
return name;
SampleInsert.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleInsert
private Sample s;
private static SessionFactory sf;
public void insert()
sf = new Configuration().configure(new File("C:/Users/ns068002/eclipse-workspace/JAXRS-HelloWorld1/src/main/java/com/javacodegeeks/enterprise/rest/jersey/hibernate.cfg.xml")).buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Sample s=(Sample) session.get(Sample.class, 1);
System.out.println(s+"2");
System.out.println(s.get_name());
session.getTransaction().commit();
SampleInsertTest.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SampleTest
Session session;
SampleInsert st;
@Before
public void setUp()
session=mock(Session.class);
st=new SampleInsert();
@Test
public void test()
Sample s=new Sample();
s.set_sid(1);
s.set_name("gopal");
Mockito.when(session.get(Sample.class,1)).thenReturn(s);
System.out.println(s+"1");
st.insert();
java hibernate
java hibernate
New contributor
New contributor
New contributor
asked Mar 20 at 11:17
GaurangaGauranga
1
1
New contributor
New contributor
In theory you shouldn't need to test that hibernate is inserting data; it is probably more effective for you to test that your interface to hibernate is called correctly. A quick google search shows lots of interest in this and at least one tutorial such as: dzone.com/articles/testing-databases-junit-and
– Gavin
Mar 20 at 11:26
Thank you for replying. But i need to check whether how much code coverage is there. so i need to use junit testing and mockito framework. @Gavin
– Gauranga
Mar 20 at 11:35
You're welcome :) You don't "have" to use Mockito, you can write your own mocks and stubs, Mockito is not a precondition of code coverage. While 100% code coverage can be consider a laudable goal, it is not always an indication of a well tested code base. You should test the bits of code you (or your team) own.
– Gavin
Mar 20 at 11:43
But how to do junit test for the above class for SampleInsert.java. Just for information. Because i was trying to do junit using mockito but i wasnot able to do it.@Gavin
– Gauranga
Mar 21 at 4:51
add a comment |
In theory you shouldn't need to test that hibernate is inserting data; it is probably more effective for you to test that your interface to hibernate is called correctly. A quick google search shows lots of interest in this and at least one tutorial such as: dzone.com/articles/testing-databases-junit-and
– Gavin
Mar 20 at 11:26
Thank you for replying. But i need to check whether how much code coverage is there. so i need to use junit testing and mockito framework. @Gavin
– Gauranga
Mar 20 at 11:35
You're welcome :) You don't "have" to use Mockito, you can write your own mocks and stubs, Mockito is not a precondition of code coverage. While 100% code coverage can be consider a laudable goal, it is not always an indication of a well tested code base. You should test the bits of code you (or your team) own.
– Gavin
Mar 20 at 11:43
But how to do junit test for the above class for SampleInsert.java. Just for information. Because i was trying to do junit using mockito but i wasnot able to do it.@Gavin
– Gauranga
Mar 21 at 4:51
In theory you shouldn't need to test that hibernate is inserting data; it is probably more effective for you to test that your interface to hibernate is called correctly. A quick google search shows lots of interest in this and at least one tutorial such as: dzone.com/articles/testing-databases-junit-and
– Gavin
Mar 20 at 11:26
In theory you shouldn't need to test that hibernate is inserting data; it is probably more effective for you to test that your interface to hibernate is called correctly. A quick google search shows lots of interest in this and at least one tutorial such as: dzone.com/articles/testing-databases-junit-and
– Gavin
Mar 20 at 11:26
Thank you for replying. But i need to check whether how much code coverage is there. so i need to use junit testing and mockito framework. @Gavin
– Gauranga
Mar 20 at 11:35
Thank you for replying. But i need to check whether how much code coverage is there. so i need to use junit testing and mockito framework. @Gavin
– Gauranga
Mar 20 at 11:35
You're welcome :) You don't "have" to use Mockito, you can write your own mocks and stubs, Mockito is not a precondition of code coverage. While 100% code coverage can be consider a laudable goal, it is not always an indication of a well tested code base. You should test the bits of code you (or your team) own.
– Gavin
Mar 20 at 11:43
You're welcome :) You don't "have" to use Mockito, you can write your own mocks and stubs, Mockito is not a precondition of code coverage. While 100% code coverage can be consider a laudable goal, it is not always an indication of a well tested code base. You should test the bits of code you (or your team) own.
– Gavin
Mar 20 at 11:43
But how to do junit test for the above class for SampleInsert.java. Just for information. Because i was trying to do junit using mockito but i wasnot able to do it.@Gavin
– Gauranga
Mar 21 at 4:51
But how to do junit test for the above class for SampleInsert.java. Just for information. Because i was trying to do junit using mockito but i wasnot able to do it.@Gavin
– Gauranga
Mar 21 at 4:51
add a comment |
1 Answer
1
active
oldest
votes
Looking at your code, I can not see how you would be able to mock/stub the Session or SessionFactory as neither of these things are "injected" into the class SampleInsert.
By "injected" I mean that the values are not passed into the class in some way, this is usually done using annotation with a framework like Spring, or via constructors.
It should be remembered that we are not testing the thing we are mocking, we are replacing the thing being mocked with a representation that is much simpler in order to test a component that makes use of the thing being mocked.
As an example of how you might use Mockito:
public interface SomethingToMock
int returnSomeValueFor(int value);
public class ToBeTested
private SomethingToMock session;
public ToBeTested(SomethingToMock session)
this.session = session;
public void methodToTestA(int value)
returnSomeValueFor(value);
public int methodToTestB(int value)
int i = returnSomeValueFor(value);
return i * i;
@RunWith(MockitoJUnitRunner.class)
public class SomeTests
@Mock
private SomethingToMock aMock;
private ToBeTested underTest;
@Before
public void setUp()
underTest = new ToBeTested(aMock);
@Test
public void testOne()
underTest.MethodToTestA(3);
verify(aMock).returnSomeValueFor(3);
@Test
public void testTwo()
when(aMock.returnSomeValueFor(3)).thenReturn(2);
int r = underTest.methodToTestB(3);
assertEqual(r, 4);
In the example above we create an interface, this represents the thing to be mocked, we should aim to only mock interfaces and only those we or our team has created.
We then have a class that we need to test that uses the interface ToBeTested
we can assume that concrete implementation of the interface are tested elsewhere in the project.ToBeTested
has two methods to test, one that has no return so has no side effects that we can see. The second method does some processing and has a side effect.
We then create a test class to test both methods, we insure it is setup to use Mockito (@RunWith(MockitoJUnitRunner.class
) we then setup a mock using @Mock
, the final setup step is to ensure our class has the mock "injected" into it, this is done in the setUp()
method.
Finally we create two tests the first verifies that the mocked method is called, we don't have to set up a when
for this in this case as no value will be returned from the method we are testing, just from the method being mocked I believe Mockito will return the default for an int.
The second test tests that a value is returned, thus we setup a when
, when the mocked method is called in the way specified in the when
the given value is returned and we can assert that the correct value is returned from the method under test, in this case using assertThat
This is the general layout of testing with Mockito. Effective testing is a huge topic, I would suggest you do some research on the web. The Mockito and JUnit docs are very good, and of course GitHub has many projects using both; one idea might be to look at the Mockito and Unit on Github and look at their testing.
Also the Mockito documentation does a very good job of explaining how, why and when to use mocking: http://static.javadoc.io/org.mockito/mockito-core/2.25.1/org/mockito/Mockito.html
I hope this helps.
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
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
);
);
Gauranga is a new contributor. Be nice, and check out our Code of Conduct.
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%2f55259507%2fhow-to-do-junit-test-for-data-base-insertion-using-hibernate%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
Looking at your code, I can not see how you would be able to mock/stub the Session or SessionFactory as neither of these things are "injected" into the class SampleInsert.
By "injected" I mean that the values are not passed into the class in some way, this is usually done using annotation with a framework like Spring, or via constructors.
It should be remembered that we are not testing the thing we are mocking, we are replacing the thing being mocked with a representation that is much simpler in order to test a component that makes use of the thing being mocked.
As an example of how you might use Mockito:
public interface SomethingToMock
int returnSomeValueFor(int value);
public class ToBeTested
private SomethingToMock session;
public ToBeTested(SomethingToMock session)
this.session = session;
public void methodToTestA(int value)
returnSomeValueFor(value);
public int methodToTestB(int value)
int i = returnSomeValueFor(value);
return i * i;
@RunWith(MockitoJUnitRunner.class)
public class SomeTests
@Mock
private SomethingToMock aMock;
private ToBeTested underTest;
@Before
public void setUp()
underTest = new ToBeTested(aMock);
@Test
public void testOne()
underTest.MethodToTestA(3);
verify(aMock).returnSomeValueFor(3);
@Test
public void testTwo()
when(aMock.returnSomeValueFor(3)).thenReturn(2);
int r = underTest.methodToTestB(3);
assertEqual(r, 4);
In the example above we create an interface, this represents the thing to be mocked, we should aim to only mock interfaces and only those we or our team has created.
We then have a class that we need to test that uses the interface ToBeTested
we can assume that concrete implementation of the interface are tested elsewhere in the project.ToBeTested
has two methods to test, one that has no return so has no side effects that we can see. The second method does some processing and has a side effect.
We then create a test class to test both methods, we insure it is setup to use Mockito (@RunWith(MockitoJUnitRunner.class
) we then setup a mock using @Mock
, the final setup step is to ensure our class has the mock "injected" into it, this is done in the setUp()
method.
Finally we create two tests the first verifies that the mocked method is called, we don't have to set up a when
for this in this case as no value will be returned from the method we are testing, just from the method being mocked I believe Mockito will return the default for an int.
The second test tests that a value is returned, thus we setup a when
, when the mocked method is called in the way specified in the when
the given value is returned and we can assert that the correct value is returned from the method under test, in this case using assertThat
This is the general layout of testing with Mockito. Effective testing is a huge topic, I would suggest you do some research on the web. The Mockito and JUnit docs are very good, and of course GitHub has many projects using both; one idea might be to look at the Mockito and Unit on Github and look at their testing.
Also the Mockito documentation does a very good job of explaining how, why and when to use mocking: http://static.javadoc.io/org.mockito/mockito-core/2.25.1/org/mockito/Mockito.html
I hope this helps.
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
add a comment |
Looking at your code, I can not see how you would be able to mock/stub the Session or SessionFactory as neither of these things are "injected" into the class SampleInsert.
By "injected" I mean that the values are not passed into the class in some way, this is usually done using annotation with a framework like Spring, or via constructors.
It should be remembered that we are not testing the thing we are mocking, we are replacing the thing being mocked with a representation that is much simpler in order to test a component that makes use of the thing being mocked.
As an example of how you might use Mockito:
public interface SomethingToMock
int returnSomeValueFor(int value);
public class ToBeTested
private SomethingToMock session;
public ToBeTested(SomethingToMock session)
this.session = session;
public void methodToTestA(int value)
returnSomeValueFor(value);
public int methodToTestB(int value)
int i = returnSomeValueFor(value);
return i * i;
@RunWith(MockitoJUnitRunner.class)
public class SomeTests
@Mock
private SomethingToMock aMock;
private ToBeTested underTest;
@Before
public void setUp()
underTest = new ToBeTested(aMock);
@Test
public void testOne()
underTest.MethodToTestA(3);
verify(aMock).returnSomeValueFor(3);
@Test
public void testTwo()
when(aMock.returnSomeValueFor(3)).thenReturn(2);
int r = underTest.methodToTestB(3);
assertEqual(r, 4);
In the example above we create an interface, this represents the thing to be mocked, we should aim to only mock interfaces and only those we or our team has created.
We then have a class that we need to test that uses the interface ToBeTested
we can assume that concrete implementation of the interface are tested elsewhere in the project.ToBeTested
has two methods to test, one that has no return so has no side effects that we can see. The second method does some processing and has a side effect.
We then create a test class to test both methods, we insure it is setup to use Mockito (@RunWith(MockitoJUnitRunner.class
) we then setup a mock using @Mock
, the final setup step is to ensure our class has the mock "injected" into it, this is done in the setUp()
method.
Finally we create two tests the first verifies that the mocked method is called, we don't have to set up a when
for this in this case as no value will be returned from the method we are testing, just from the method being mocked I believe Mockito will return the default for an int.
The second test tests that a value is returned, thus we setup a when
, when the mocked method is called in the way specified in the when
the given value is returned and we can assert that the correct value is returned from the method under test, in this case using assertThat
This is the general layout of testing with Mockito. Effective testing is a huge topic, I would suggest you do some research on the web. The Mockito and JUnit docs are very good, and of course GitHub has many projects using both; one idea might be to look at the Mockito and Unit on Github and look at their testing.
Also the Mockito documentation does a very good job of explaining how, why and when to use mocking: http://static.javadoc.io/org.mockito/mockito-core/2.25.1/org/mockito/Mockito.html
I hope this helps.
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
add a comment |
Looking at your code, I can not see how you would be able to mock/stub the Session or SessionFactory as neither of these things are "injected" into the class SampleInsert.
By "injected" I mean that the values are not passed into the class in some way, this is usually done using annotation with a framework like Spring, or via constructors.
It should be remembered that we are not testing the thing we are mocking, we are replacing the thing being mocked with a representation that is much simpler in order to test a component that makes use of the thing being mocked.
As an example of how you might use Mockito:
public interface SomethingToMock
int returnSomeValueFor(int value);
public class ToBeTested
private SomethingToMock session;
public ToBeTested(SomethingToMock session)
this.session = session;
public void methodToTestA(int value)
returnSomeValueFor(value);
public int methodToTestB(int value)
int i = returnSomeValueFor(value);
return i * i;
@RunWith(MockitoJUnitRunner.class)
public class SomeTests
@Mock
private SomethingToMock aMock;
private ToBeTested underTest;
@Before
public void setUp()
underTest = new ToBeTested(aMock);
@Test
public void testOne()
underTest.MethodToTestA(3);
verify(aMock).returnSomeValueFor(3);
@Test
public void testTwo()
when(aMock.returnSomeValueFor(3)).thenReturn(2);
int r = underTest.methodToTestB(3);
assertEqual(r, 4);
In the example above we create an interface, this represents the thing to be mocked, we should aim to only mock interfaces and only those we or our team has created.
We then have a class that we need to test that uses the interface ToBeTested
we can assume that concrete implementation of the interface are tested elsewhere in the project.ToBeTested
has two methods to test, one that has no return so has no side effects that we can see. The second method does some processing and has a side effect.
We then create a test class to test both methods, we insure it is setup to use Mockito (@RunWith(MockitoJUnitRunner.class
) we then setup a mock using @Mock
, the final setup step is to ensure our class has the mock "injected" into it, this is done in the setUp()
method.
Finally we create two tests the first verifies that the mocked method is called, we don't have to set up a when
for this in this case as no value will be returned from the method we are testing, just from the method being mocked I believe Mockito will return the default for an int.
The second test tests that a value is returned, thus we setup a when
, when the mocked method is called in the way specified in the when
the given value is returned and we can assert that the correct value is returned from the method under test, in this case using assertThat
This is the general layout of testing with Mockito. Effective testing is a huge topic, I would suggest you do some research on the web. The Mockito and JUnit docs are very good, and of course GitHub has many projects using both; one idea might be to look at the Mockito and Unit on Github and look at their testing.
Also the Mockito documentation does a very good job of explaining how, why and when to use mocking: http://static.javadoc.io/org.mockito/mockito-core/2.25.1/org/mockito/Mockito.html
I hope this helps.
Looking at your code, I can not see how you would be able to mock/stub the Session or SessionFactory as neither of these things are "injected" into the class SampleInsert.
By "injected" I mean that the values are not passed into the class in some way, this is usually done using annotation with a framework like Spring, or via constructors.
It should be remembered that we are not testing the thing we are mocking, we are replacing the thing being mocked with a representation that is much simpler in order to test a component that makes use of the thing being mocked.
As an example of how you might use Mockito:
public interface SomethingToMock
int returnSomeValueFor(int value);
public class ToBeTested
private SomethingToMock session;
public ToBeTested(SomethingToMock session)
this.session = session;
public void methodToTestA(int value)
returnSomeValueFor(value);
public int methodToTestB(int value)
int i = returnSomeValueFor(value);
return i * i;
@RunWith(MockitoJUnitRunner.class)
public class SomeTests
@Mock
private SomethingToMock aMock;
private ToBeTested underTest;
@Before
public void setUp()
underTest = new ToBeTested(aMock);
@Test
public void testOne()
underTest.MethodToTestA(3);
verify(aMock).returnSomeValueFor(3);
@Test
public void testTwo()
when(aMock.returnSomeValueFor(3)).thenReturn(2);
int r = underTest.methodToTestB(3);
assertEqual(r, 4);
In the example above we create an interface, this represents the thing to be mocked, we should aim to only mock interfaces and only those we or our team has created.
We then have a class that we need to test that uses the interface ToBeTested
we can assume that concrete implementation of the interface are tested elsewhere in the project.ToBeTested
has two methods to test, one that has no return so has no side effects that we can see. The second method does some processing and has a side effect.
We then create a test class to test both methods, we insure it is setup to use Mockito (@RunWith(MockitoJUnitRunner.class
) we then setup a mock using @Mock
, the final setup step is to ensure our class has the mock "injected" into it, this is done in the setUp()
method.
Finally we create two tests the first verifies that the mocked method is called, we don't have to set up a when
for this in this case as no value will be returned from the method we are testing, just from the method being mocked I believe Mockito will return the default for an int.
The second test tests that a value is returned, thus we setup a when
, when the mocked method is called in the way specified in the when
the given value is returned and we can assert that the correct value is returned from the method under test, in this case using assertThat
This is the general layout of testing with Mockito. Effective testing is a huge topic, I would suggest you do some research on the web. The Mockito and JUnit docs are very good, and of course GitHub has many projects using both; one idea might be to look at the Mockito and Unit on Github and look at their testing.
Also the Mockito documentation does a very good job of explaining how, why and when to use mocking: http://static.javadoc.io/org.mockito/mockito-core/2.25.1/org/mockito/Mockito.html
I hope this helps.
edited 2 days ago
answered 2 days ago
GavinGavin
712719
712719
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
add a comment |
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
For completeness it is possible to Mock classes, however in my opinion it is preferable to mock interfaces where possible
– Gavin
2 days ago
add a comment |
Gauranga is a new contributor. Be nice, and check out our Code of Conduct.
Gauranga is a new contributor. Be nice, and check out our Code of Conduct.
Gauranga is a new contributor. Be nice, and check out our Code of Conduct.
Gauranga is a new contributor. Be nice, and check out our Code of Conduct.
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%2f55259507%2fhow-to-do-junit-test-for-data-base-insertion-using-hibernate%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
In theory you shouldn't need to test that hibernate is inserting data; it is probably more effective for you to test that your interface to hibernate is called correctly. A quick google search shows lots of interest in this and at least one tutorial such as: dzone.com/articles/testing-databases-junit-and
– Gavin
Mar 20 at 11:26
Thank you for replying. But i need to check whether how much code coverage is there. so i need to use junit testing and mockito framework. @Gavin
– Gauranga
Mar 20 at 11:35
You're welcome :) You don't "have" to use Mockito, you can write your own mocks and stubs, Mockito is not a precondition of code coverage. While 100% code coverage can be consider a laudable goal, it is not always an indication of a well tested code base. You should test the bits of code you (or your team) own.
– Gavin
Mar 20 at 11:43
But how to do junit test for the above class for SampleInsert.java. Just for information. Because i was trying to do junit using mockito but i wasnot able to do it.@Gavin
– Gauranga
Mar 21 at 4:51