Vivek R | 4 Nov 14:35 2008
Picon

exactly(n) function in JMock

Hi,
I am facing a slightly weird problem. I set an expectation as

exactly(n).of(<mock-obj>).f()

Bug
Suppose the function f() is called 5 times; For any n < 5, the expectation fails. However, if I provide the value of n > 5, it passes for all!!
Eg: exactly(100).of(<mock-obj>).f()
The above expectation passes, even though the function f() is called only 5 times!

Any thoughts ?

PS: The expectation is under a context and the syntax is perfectly fine. In short, the java file compiles fine!

-Vivek


josephpford | 5 Nov 21:44 2008
Picon

testing that the class under test throws exception correctly

Good day,

I'm trying to test that my Class Under Test actually throws an exception when I believe it will. I've created some sample code and pasted it all below. Please see the *** areas in the below code, and I've also included my supporting classes code if you need it at the bottom of this post.

Here's the problem I'm having. JMock only allows you to put Mocked objects in your "Expectations" section. I want to verify that when a Mocked object returns a value which will cause my Class Under Test to throw an exception, that it actually does throw an exception. I've verified that my code works by adding a "System.out.println("Got to here");" statement in the "catch" block below, but that's not repeatable, automated Unit testing. Please help me understand how I can do this in a repeatable, automated fashion.

Regards,
Joseph Ford

//PublisherTest.java
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class PublisherTest {
Mockery context = new Mockery();

<at> Test
public void testGetMessagesFromOneSubscriberReturnsException() {
//setup
final Subscriber subscriber = context.mock(Subscriber.class);
final Publisher publisher = new Publisher();
publisher.add(subscriber);


//expectations
context.checking(new Expectations() {{
exactly(1).of(subscriber).getSubscriberID(); will(returnValue(2));
//***NOT ALLOWED***exactly(1).of(publisher).getMessagesFromOneSubscriber(1); will(throwException(new NoSuchElementException ()));
}});

//execute
try {
<at> SuppressWarnings("unused")
Iterator<String> anIterator = publisher.getMessagesFromOneSubscriber(1);
} catch (NoSuchElementException exception) {
//***How do I test that I got to here?***
}

//verify
context.assertIsSatisfied();
}
}

//Publisher.java
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.NoSuchElementException;

public class Publisher {
ArrayList<Subscriber> list;

public Publisher() {
list = new ArrayList<Subscriber>();
}

public void add(Subscriber subscriber) {
list.add(subscriber);
}

public void publish(String message) {
for (int j = 0; j < list.size(); j++)
list.get(j).receive(message);
}

public ListIterator<String> getMessagesFromOneSubscriber(int subscriberID) throws NoSuchElementException {
ListIterator<Subscriber> anIterator = list.listIterator(0);
while (anIterator.hasNext()) {
if (anIterator.next().getSubscriberID() == subscriberID)
return anIterator.previous().getHistoricalMessages();
}
throw new NoSuchElementException();
}
}


//Subscriber.java
import java.util.ListIterator;

public interface Subscriber {
public void receive(String message);
public int getSubscriberID();
public ListIterator<String> getHistoricalMessages();
}

Chris O'Connell | 5 Nov 21:51 2008

RE: testing that the class under test throws exception correctly

Modify your code to look like this (there are many ways to do this):

//execute
try {
<at> SuppressWarnings("unused")
Iterator<String> anIterator = publisher.getMessagesFromOneSubscriber(1);

fail(“Did not throw an exception from ‘getMessagesFromOneSubscriber()”);
} catch (NoSuchElementException exception) {
// do nothing, expected
}

 

If you do the above, your test will fail if you don’t throw any exception, and if you throw any exception other than the NoSuchElementException, your test will also fail.

 

or, you could annotate the test method like this (and remove the try/catch block from the test code altogether):

 

<at> Test(expected= NoSuchElementException.class)
public void testGetMessagesFromOneSubscriberReturnsException() throws Exception {

 

}

 

 

From: josephpford-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org [mailto:josephpford-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org]
Sent: Wednesday, November 05, 2008 2:45 PM
To: user-sXN/XchZ9OexIXFVlbCvtR2eb7JE58TQ@public.gmane.org
Subject: [jmock-user] testing that the class under test throws exception correctly

 

Good day,

I'm trying to test that my Class Under Test actually throws an exception when I believe it will. I've created some sample code and pasted it all below. Please see the *** areas in the below code, and I've also included my supporting classes code if you need it at the bottom of this post.

Here's the problem I'm having. JMock only allows you to put Mocked objects in your "Expectations" section. I want to verify that when a Mocked object returns a value which will cause my Class Under Test to throw an exception, that it actually does throw an exception. I've verified that my code works by adding a "System.out.println("Got to here");" statement in the "catch" block below, but that's not repeatable, automated Unit testing. Please help me understand how I can do this in a repeatable, automated fashion.

Regards,
Joseph Ford

//PublisherTest.java
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class PublisherTest {
Mockery context = new Mockery();

<at> Test
public void testGetMessagesFromOneSubscriberReturnsException() {
//setup
final Subscriber subscriber = context.mock(Subscriber.class);
final Publisher publisher = new Publisher();
publisher.add(subscriber);


//expectations
context.checking(new Expectations() {{
exactly(1).of(subscriber).getSubscriberID(); will(returnValue(2));
//***NOT ALLOWED***exactly(1).of(publisher).getMessagesFromOneSubscriber(1); will(throwException(new NoSuchElementException ()));
}});

//execute
try {
<at> SuppressWarnings("unused")
Iterator<String> anIterator = publisher.getMessagesFromOneSubscriber(1);
} catch (NoSuchElementException exception) {
//***How do I test that I got to here?***
}

//verify
context.assertIsSatisfied();
}
}

//Publisher.java
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.NoSuchElementException;

public class Publisher {
ArrayList<Subscriber> list;

public Publisher() {
list = new ArrayList<Subscriber>();
}

public void add(Subscriber subscriber) {
list.add(subscriber);
}

public void publish(String message) {
for (int j = 0; j < list.size(); j++)
list.get(j).receive(message);
}

public ListIterator<String> getMessagesFromOneSubscriber(int subscriberID) throws NoSuchElementException {
ListIterator<Subscriber> anIterator = list.listIterator(0);
while (anIterator.hasNext()) {
if (anIterator.next().getSubscriberID() == subscriberID)
return anIterator.previous().getHistoricalMessages();
}
throw new NoSuchElementException();
}
}


//Subscriber.java
import java.util.ListIterator;

public interface Subscriber {
public void receive(String message);
public int getSubscriberID();
public ListIterator<String> getHistoricalMessages();
}

No virus found in this incoming message.
Checked by AVG - http://www.avg.com
Version: 8.0.175 / Virus Database: 270.8.6/1769 - Release Date: 11/5/2008 5:36 PM

Piers | 11 Nov 17:03 2008

How to mock private fields and static classes?

Hi

I am unit testing some legacy code and am having difficulty mocking 
certain objects, private fields and a static class. As much as possible 
I would like to leave the legacy code unchanged.

Could anyone shed some light on how this might be done or point me in 
the right direction.

Here is a small example to illustrate what I am talking about. In this 
case I want to test method m but can't because I am unable to mock b or 
the static method getIntValue().

Class A{

// b is initialised by some method of class A
private B b

	public void m(){

		//I want to mock b but it is private and cannot be 				//accessed from 
outside the class
		String s = b.getName();

		//I want to mock the static method getIntValue()
		int i = C.getIntValue();

	}
}

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email

Nat Pryce | 11 Nov 17:49 2008
Picon

Re: How to mock private fields and static classes?

How does A get its reference to b?  Where it is given b, pass a mock
instance instead of a real one.

If that is too tightly coupled to do that (e.g. b comes from a static
method) then JMock won't let you mock it.  If your code is tightly
coupled and you don't want to change it, then mock objects are not a
good tool to use.  Instead cover the legacy code with coarse-grained
tests, decouple new code from the legacy code with interfaces that are
easy to mock, and only introduce mocks into the tests of the legacy
code when you have start to refactor it.

--Nat

2008/11/11 Piers <piers@...>:
> Hi
>
> I am unit testing some legacy code and am having difficulty mocking certain
> objects, private fields and a static class. As much as possible I would like
> to leave the legacy code unchanged.
>
> Could anyone shed some light on how this might be done or point me in the
> right direction.
>
> Here is a small example to illustrate what I am talking about. In this case
> I want to test method m but can't because I am unable to mock b or the
> static method getIntValue().
>
> Class A{
>
> // b is initialised by some method of class A
> private B b
>
>        public void m(){
>
>                //I want to mock b but it is private and cannot be
>                    //accessed from outside the class
>                String s = b.getName();
>
>                //I want to mock the static method getIntValue()
>                int i = C.getIntValue();
>
>        }
> }
>
> ---------------------------------------------------------------------
> To unsubscribe from this list, please visit:
>
>   http://xircles.codehaus.org/manage_email
>
>
>

--

-- 
Random musings at http://www.natpryce.com

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email

Piers | 11 Nov 17:52 2008

Re: How to mock private fields and static classes?

Thank you Nat for your clear and quick reply.

Piers

Nat Pryce wrote:
> How does A get its reference to b?  Where it is given b, pass a mock
> instance instead of a real one.
> 
> If that is too tightly coupled to do that (e.g. b comes from a static
> method) then JMock won't let you mock it.  If your code is tightly
> coupled and you don't want to change it, then mock objects are not a
> good tool to use.  Instead cover the legacy code with coarse-grained
> tests, decouple new code from the legacy code with interfaces that are
> easy to mock, and only introduce mocks into the tests of the legacy
> code when you have start to refactor it.
> 
> --Nat
> 
> 2008/11/11 Piers <piers@...>:
>> Hi
>>
>> I am unit testing some legacy code and am having difficulty mocking certain
>> objects, private fields and a static class. As much as possible I would like
>> to leave the legacy code unchanged.
>>
>> Could anyone shed some light on how this might be done or point me in the
>> right direction.
>>
>> Here is a small example to illustrate what I am talking about. In this case
>> I want to test method m but can't because I am unable to mock b or the
>> static method getIntValue().
>>
>> Class A{
>>
>> // b is initialised by some method of class A
>> private B b
>>
>>        public void m(){
>>
>>                //I want to mock b but it is private and cannot be
>>                    //accessed from outside the class
>>                String s = b.getName();
>>
>>                //I want to mock the static method getIntValue()
>>                int i = C.getIntValue();
>>
>>        }
>> }
>>
>> ---------------------------------------------------------------------
>> To unsubscribe from this list, please visit:
>>
>>   http://xircles.codehaus.org/manage_email
>>
>>
>>
> 
> 
> 

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email

Redmund reynolds | 11 Nov 18:32 2008
Picon

Testing a method taking no input parameters


Hi,

I am new to JMock. I am using version 2.5. I tried one example with JMock
and it worked fine. Then I tried to implement it in our project, but ruuning
into problems. Here is the situation.

I have service class like this

public class UserManagementServicesImpl implements IUserManagementService {

	public UserManagementServicesImpl(){
		super();
	}
	
	private IOccupationCodeDAO occuCodeDAO;
	private ICountryCodeDAO countryCodeDAO;
	private IDegreeCodeDAO degreeCodeDAO;
	private IIndustryTypeCodeDAO industryCodeDAO;
	
	public LookupCodesVo getLookupDataForRegistration() throws
APIUserServicesException{
		logger.debug("Begin
UserManagementServicesImpl::getLookupDataForRegistration");
		LookupCodesVo lookupCodesVo=null;
		try{
			lookupCodesVo=new LookupCodesVo();
			lookupCodesVo.setOccuCodes(occuCodeDAO.getOccupationCodes());
			lookupCodesVo.setCountryCodes(countryCodeDAO.getCountryCodes());
			lookupCodesVo.setDegreeCodes(degreeCodeDAO.getDegreeCodes());
			lookupCodesVo.setIndustryCodes(industryCodeDAO.getIndustryTypeCodes());
		} catch (APIUserServicesException exp) {
			logger.error("Exception
UserManagementServicesImpl:getLookupDataForRegistration::"+exp.getMessage());
			exp.printStackTrace();
			throw exp;
		}catch (Exception e) {
			logger.error("Exception
UserManagementServicesImpl:getLookupDataForRegistration::"+e.getMessage());
			e.printStackTrace();
			throw new
APIUserServicesException("Exception",e.getMessage(),"getLookupDataForRegistration",e.getClass().getName()
);
		}
		logger.debug("End
UserManagementServicesImpl::getLookupDataForRegistration");
		return lookupCodesVo;
	}

............. and setters for DAOs

I have unit test case like below

public class UserRegistrationTest extends UserMngmtServiceTest {

	public UserRegistrationTest(){
		countryCodeDAO=context.mock(ICountryCodeDAO.class);
		degreeCodeDAO=context.mock(IDegreeCodeDAO.class);
		industryCodeDAO=context.mock(IIndustryTypeCodeDAO.class);
		occuCodeDAO=context.mock(IOccupationCodeDAO.class);
		
		userMngmtServie.setCountryCodeDAO(countryCodeDAO);
		userMngmtServie.setDegreeCodeDAO(degreeCodeDAO);
		userMngmtServie.setIndustryCodeDAO(industryCodeDAO);
		userMngmtServie.setOccuCodeDAO(occuCodeDAO);
	}

	public void testGetLookupDataForRegistration(){
		try{
			context.checking(new Expectations(){{
				oneOf(occuCodeDAO.getOccupationCodes());
				will(returnEnumeration(preparOccupationCodes()));					
			
				oneOf(countryCodeDAO.getCountryCodes());
				will(returnEnumeration(preparCountryCodes()));			
							
				oneOf(degreeCodeDAO.getDegreeCodes());
				will(returnEnumeration(preparDegreeCodes()));							
							
				oneOf(industryCodeDAO.getIndustryTypeCodes());
				will(returnEnumeration(preparIndustryCodes()));
			}});
			
			LookupCodesVo
lookupCodesVo=userMngmtServie.getLookupDataForRegistration();
			context.assertIsSatisfied();
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private ArrayList<CountryCode> preparCountryCodes(){
	
		ArrayList<CountryCode> countryCodeList=new ArrayList<CountryCode>();
		
		CountryCode usa=new CountryCode();
		usa.setCountryId(new Integer(1));
		usa.setCountryName("United States Of America");
		countryCodeList.add(usa);
		
		CountryCode uk=new CountryCode();
		uk.setCountryId(new Integer(2));
		uk.setCountryName("United Kingdom");
		countryCodeList.add(uk);
		
		return countryCodeList;
	}
	
	private ArrayList<DegreeCode> preparDegreeCodes(){
		
		ArrayList<DegreeCode> degreeCodeList=new ArrayList<DegreeCode>();
		
		DegreeCode bs=new DegreeCode();
		bs.setDegreeTypeId(new Integer(1));
		bs.setDegreeTypeDesc("Bachelors in Science");
		degreeCodeList.add(bs);
		
		DegreeCode ms=new DegreeCode();
		ms.setDegreeTypeId(new Integer(2));
		ms.setDegreeTypeDesc("Masters in Science");
		degreeCodeList.add(ms);
		
		return degreeCodeList;
	}
	
	private ArrayList<IndustryTypeCode> preparIndustryCodes(){
		
		ArrayList<IndustryTypeCode> industryCodeList=new
ArrayList<IndustryTypeCode>();
		
		IndustryTypeCode it=new IndustryTypeCode();
		it.setIndustryTypeId(new Integer(1));
		it.setIndustryTypeDesc("Information Technology");
		industryCodeList.add(it);
		
		IndustryTypeCode acct=new IndustryTypeCode();
		acct.setIndustryTypeId(new Integer(4));
		acct.setIndustryTypeDesc("Accounting");
		industryCodeList.add(acct);
		
		
		return industryCodeList;
	}
	
	private ArrayList<OccupationCode> preparOccupationCodes(){
		
		ArrayList<OccupationCode> occuCodeList=new ArrayList<OccupationCode>();
		
		OccupationCode programmer=new OccupationCode();
		programmer.setOccupationId(new Integer(3));
		programmer.setOccupationDescription("Computer Programmer");
		occuCodeList.add(programmer);
		
		
		return occuCodeList;
	}
}

But it is throwing an error like below...

unexpected invocation: iOccupationCodeDAO.getOccupationCodes()
no expectations specified: did you...
 - forget to start an expectation with a cardinality clause?
 - call a mocked method to specify the parameter of an expectation?
what happened before this: nothing!
	at
org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:56)
	at org.jmock.Mockery.dispatch(Mockery.java:218)
	at org.jmock.Mockery.access$000(Mockery.java:43)
	at org.jmock.Mockery$MockObject.invoke(Mockery.java:258)
	at org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
	at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
	at
org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
	at $Proxy3.getOccupationCodes(Unknown Source)
	at
com.sumobrain.api.business.service.SampleTest$1.<init>(SampleTest.java:47)
	at
com.sumobrain.api.business.service.SampleTest.testGetLookupDataForRegistration(SampleTest.java:46)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at junit.framework.TestCase.runTest(TestCase.java:168)
	at junit.framework.TestCase.runBare(TestCase.java:134)
	at junit.framework.TestResult$1.protect(TestResult.java:110)
	at junit.framework.TestResult.runProtected(TestResult.java:128)
	at junit.framework.TestResult.run(TestResult.java:113)
	at junit.framework.TestCase.run(TestCase.java:124)
	at junit.framework.TestSuite.runTest(TestSuite.java:232)
	at junit.framework.TestSuite.run(TestSuite.java:227)
	at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
	at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
	at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
	at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
	at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
	at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Any Help is really appreciated.

Thanks:working:
--

-- 
View this message in context: http://www.nabble.com/Testing-a-method-taking-no-input-parameters-tp20444371p20444371.html
Sent from the jMock - User mailing list archive at Nabble.com.

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email

Vivek R | 11 Nov 19:31 2008
Picon

Re: Testing a method taking no input parameters

Check whether all methods are mocked...each and every one..that is the problem..

-viv

On Tue, Nov 11, 2008 at 11:02 PM, Redmund reynolds <dayal_407-/E1597aS9LQAvxtiuMwx3w@public.gmane.org> wrote:

Hi,

I am new to JMock. I am using version 2.5. I tried one example with JMock
and it worked fine. Then I tried to implement it in our project, but ruuning
into problems. Here is the situation.

I have service class like this

public class UserManagementServicesImpl implements IUserManagementService {

       public UserManagementServicesImpl(){
               super();
       }

       private IOccupationCodeDAO occuCodeDAO;
       private ICountryCodeDAO countryCodeDAO;
       private IDegreeCodeDAO degreeCodeDAO;
       private IIndustryTypeCodeDAO industryCodeDAO;

       public LookupCodesVo getLookupDataForRegistration() throws
APIUserServicesException{
               logger.debug("Begin
UserManagementServicesImpl::getLookupDataForRegistration");
               LookupCodesVo lookupCodesVo=null;
               try{
                       lookupCodesVo=new LookupCodesVo();
                       lookupCodesVo.setOccuCodes(occuCodeDAO.getOccupationCodes());
                       lookupCodesVo.setCountryCodes(countryCodeDAO.getCountryCodes());
                       lookupCodesVo.setDegreeCodes(degreeCodeDAO.getDegreeCodes());
                       lookupCodesVo.setIndustryCodes(industryCodeDAO.getIndustryTypeCodes());
               } catch (APIUserServicesException exp) {
                       logger.error("Exception
UserManagementServicesImpl:getLookupDataForRegistration::"+exp.getMessage());
                       exp.printStackTrace();
                       throw exp;
               }catch (Exception e) {
                       logger.error("Exception
UserManagementServicesImpl:getLookupDataForRegistration::"+e.getMessage());
                       e.printStackTrace();
                       throw new
APIUserServicesException("Exception",e.getMessage(),"getLookupDataForRegistration",e.getClass().getName()
);
               }
               logger.debug("End
UserManagementServicesImpl::getLookupDataForRegistration");
               return lookupCodesVo;
       }

............. and setters for DAOs

I have unit test case like below

public class UserRegistrationTest extends UserMngmtServiceTest {

       public UserRegistrationTest(){
               countryCodeDAO=context.mock(ICountryCodeDAO.class);
               degreeCodeDAO=context.mock(IDegreeCodeDAO.class);
               industryCodeDAO=context.mock(IIndustryTypeCodeDAO.class);
               occuCodeDAO=context.mock(IOccupationCodeDAO.class);

               userMngmtServie.setCountryCodeDAO(countryCodeDAO);
               userMngmtServie.setDegreeCodeDAO(degreeCodeDAO);
               userMngmtServie.setIndustryCodeDAO(industryCodeDAO);
               userMngmtServie.setOccuCodeDAO(occuCodeDAO);
       }

       public void testGetLookupDataForRegistration(){
               try{
                       context.checking(new Expectations(){{
                               oneOf(occuCodeDAO.getOccupationCodes());
                               will(returnEnumeration(preparOccupationCodes()));

                               oneOf(countryCodeDAO.getCountryCodes());
                               will(returnEnumeration(preparCountryCodes()));

                               oneOf(degreeCodeDAO.getDegreeCodes());
                               will(returnEnumeration(preparDegreeCodes()));

                               oneOf(industryCodeDAO.getIndustryTypeCodes());
                               will(returnEnumeration(preparIndustryCodes()));
                       }});

                       LookupCodesVo
lookupCodesVo=userMngmtServie.getLookupDataForRegistration();
                       context.assertIsSatisfied();

               }catch (Exception e) {
                       e.printStackTrace();
               }
       }

       private ArrayList<CountryCode> preparCountryCodes(){

               ArrayList<CountryCode> countryCodeList=new ArrayList<CountryCode>();

               CountryCode usa=new CountryCode();
               usa.setCountryId(new Integer(1));
               usa.setCountryName("United States Of America");
               countryCodeList.add(usa);

               CountryCode uk=new CountryCode();
               uk.setCountryId(new Integer(2));
               uk.setCountryName("United Kingdom");
               countryCodeList.add(uk);

               return countryCodeList;
       }

       private ArrayList<DegreeCode> preparDegreeCodes(){

               ArrayList<DegreeCode> degreeCodeList=new ArrayList<DegreeCode>();

               DegreeCode bs=new DegreeCode();
               bs.setDegreeTypeId(new Integer(1));
               bs.setDegreeTypeDesc("Bachelors in Science");
               degreeCodeList.add(bs);

               DegreeCode ms=new DegreeCode();
               ms.setDegreeTypeId(new Integer(2));
               ms.setDegreeTypeDesc("Masters in Science");
               degreeCodeList.add(ms);

               return degreeCodeList;
       }

       private ArrayList<IndustryTypeCode> preparIndustryCodes(){

               ArrayList<IndustryTypeCode> industryCodeList=new
ArrayList<IndustryTypeCode>();

               IndustryTypeCode it=new IndustryTypeCode();
               it.setIndustryTypeId(new Integer(1));
               it.setIndustryTypeDesc("Information Technology");
               industryCodeList.add(it);

               IndustryTypeCode acct=new IndustryTypeCode();
               acct.setIndustryTypeId(new Integer(4));
               acct.setIndustryTypeDesc("Accounting");
               industryCodeList.add(acct);


               return industryCodeList;
       }

       private ArrayList<OccupationCode> preparOccupationCodes(){

               ArrayList<OccupationCode> occuCodeList=new ArrayList<OccupationCode>();

               OccupationCode programmer=new OccupationCode();
               programmer.setOccupationId(new Integer(3));
               programmer.setOccupationDescription("Computer Programmer");
               occuCodeList.add(programmer);


               return occuCodeList;
       }
}

But it is throwing an error like below...

unexpected invocation: iOccupationCodeDAO.getOccupationCodes()
no expectations specified: did you...
 - forget to start an expectation with a cardinality clause?
 - call a mocked method to specify the parameter of an expectation?
what happened before this: nothing!
       at
org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:56)
       at org.jmock.Mockery.dispatch(Mockery.java:218)
       at org.jmock.Mockery.access$000(Mockery.java:43)
       at org.jmock.Mockery$MockObject.invoke(Mockery.java:258)
       at org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
       at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
       at
org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
       at $Proxy3.getOccupationCodes(Unknown Source)
       at
com.sumobrain.api.business.service.SampleTest$1.<init>(SampleTest.java:47)
       at
com.sumobrain.api.business.service.SampleTest.testGetLookupDataForRegistration(SampleTest.java:46)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
       at java.lang.reflect.Method.invoke(Unknown Source)
       at junit.framework.TestCase.runTest(TestCase.java:168)
       at junit.framework.TestCase.runBare(TestCase.java:134)
       at junit.framework.TestResult$1.protect(TestResult.java:110)
       at junit.framework.TestResult.runProtected(TestResult.java:128)
       at junit.framework.TestResult.run(TestResult.java:113)
       at junit.framework.TestCase.run(TestCase.java:124)
       at junit.framework.TestSuite.runTest(TestSuite.java:232)
       at junit.framework.TestSuite.run(TestSuite.java:227)
       at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
       at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
       at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Any Help is really appreciated.

Thanks:working:
--
View this message in context: http://www.nabble.com/Testing-a-method-taking-no-input-parameters-tp20444371p20444371.html
Sent from the jMock - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

   http://xircles.codehaus.org/manage_email



Vivek R | 11 Nov 19:31 2008
Picon

Re: Testing a method taking no input parameters

More specifically, guess u did not mock "iOccupationCodeDAO.getOccupationCodes()" this method..Check again..

viv

On Wed, Nov 12, 2008 at 12:01 AM, Vivek R <vivmbbs-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
Check whether all methods are mocked...each and every one..that is the problem..

-viv

On Tue, Nov 11, 2008 at 11:02 PM, Redmund reynolds <dayal_407-/E1597aS9LQAvxtiuMwx3w@public.gmane.org> wrote:

Hi,

I am new to JMock. I am using version 2.5. I tried one example with JMock
and it worked fine. Then I tried to implement it in our project, but ruuning
into problems. Here is the situation.

I have service class like this

public class UserManagementServicesImpl implements IUserManagementService {

       public UserManagementServicesImpl(){
               super();
       }

       private IOccupationCodeDAO occuCodeDAO;
       private ICountryCodeDAO countryCodeDAO;
       private IDegreeCodeDAO degreeCodeDAO;
       private IIndustryTypeCodeDAO industryCodeDAO;

       public LookupCodesVo getLookupDataForRegistration() throws
APIUserServicesException{
               logger.debug("Begin
UserManagementServicesImpl::getLookupDataForRegistration");
               LookupCodesVo lookupCodesVo=null;
               try{
                       lookupCodesVo=new LookupCodesVo();
                       lookupCodesVo.setOccuCodes(occuCodeDAO.getOccupationCodes());
                       lookupCodesVo.setCountryCodes(countryCodeDAO.getCountryCodes());
                       lookupCodesVo.setDegreeCodes(degreeCodeDAO.getDegreeCodes());
                       lookupCodesVo.setIndustryCodes(industryCodeDAO.getIndustryTypeCodes());
               } catch (APIUserServicesException exp) {
                       logger.error("Exception
UserManagementServicesImpl:getLookupDataForRegistration::"+exp.getMessage());
                       exp.printStackTrace();
                       throw exp;
               }catch (Exception e) {
                       logger.error("Exception
UserManagementServicesImpl:getLookupDataForRegistration::"+e.getMessage());
                       e.printStackTrace();
                       throw new
APIUserServicesException("Exception",e.getMessage(),"getLookupDataForRegistration",e.getClass().getName()
);
               }
               logger.debug("End
UserManagementServicesImpl::getLookupDataForRegistration");
               return lookupCodesVo;
       }

............. and setters for DAOs

I have unit test case like below

public class UserRegistrationTest extends UserMngmtServiceTest {

       public UserRegistrationTest(){
               countryCodeDAO=context.mock(ICountryCodeDAO.class);
               degreeCodeDAO=context.mock(IDegreeCodeDAO.class);
               industryCodeDAO=context.mock(IIndustryTypeCodeDAO.class);
               occuCodeDAO=context.mock(IOccupationCodeDAO.class);

               userMngmtServie.setCountryCodeDAO(countryCodeDAO);
               userMngmtServie.setDegreeCodeDAO(degreeCodeDAO);
               userMngmtServie.setIndustryCodeDAO(industryCodeDAO);
               userMngmtServie.setOccuCodeDAO(occuCodeDAO);
       }

       public void testGetLookupDataForRegistration(){
               try{
                       context.checking(new Expectations(){{
                               oneOf(occuCodeDAO.getOccupationCodes());
                               will(returnEnumeration(preparOccupationCodes()));

                               oneOf(countryCodeDAO.getCountryCodes());
                               will(returnEnumeration(preparCountryCodes()));

                               oneOf(degreeCodeDAO.getDegreeCodes());
                               will(returnEnumeration(preparDegreeCodes()));

                               oneOf(industryCodeDAO.getIndustryTypeCodes());
                               will(returnEnumeration(preparIndustryCodes()));
                       }});

                       LookupCodesVo
lookupCodesVo=userMngmtServie.getLookupDataForRegistration();
                       context.assertIsSatisfied();

               }catch (Exception e) {
                       e.printStackTrace();
               }
       }

       private ArrayList<CountryCode> preparCountryCodes(){

               ArrayList<CountryCode> countryCodeList=new ArrayList<CountryCode>();

               CountryCode usa=new CountryCode();
               usa.setCountryId(new Integer(1));
               usa.setCountryName("United States Of America");
               countryCodeList.add(usa);

               CountryCode uk=new CountryCode();
               uk.setCountryId(new Integer(2));
               uk.setCountryName("United Kingdom");
               countryCodeList.add(uk);

               return countryCodeList;
       }

       private ArrayList<DegreeCode> preparDegreeCodes(){

               ArrayList<DegreeCode> degreeCodeList=new ArrayList<DegreeCode>();

               DegreeCode bs=new DegreeCode();
               bs.setDegreeTypeId(new Integer(1));
               bs.setDegreeTypeDesc("Bachelors in Science");
               degreeCodeList.add(bs);

               DegreeCode ms=new DegreeCode();
               ms.setDegreeTypeId(new Integer(2));
               ms.setDegreeTypeDesc("Masters in Science");
               degreeCodeList.add(ms);

               return degreeCodeList;
       }

       private ArrayList<IndustryTypeCode> preparIndustryCodes(){

               ArrayList<IndustryTypeCode> industryCodeList=new
ArrayList<IndustryTypeCode>();

               IndustryTypeCode it=new IndustryTypeCode();
               it.setIndustryTypeId(new Integer(1));
               it.setIndustryTypeDesc("Information Technology");
               industryCodeList.add(it);

               IndustryTypeCode acct=new IndustryTypeCode();
               acct.setIndustryTypeId(new Integer(4));
               acct.setIndustryTypeDesc("Accounting");
               industryCodeList.add(acct);


               return industryCodeList;
       }

       private ArrayList<OccupationCode> preparOccupationCodes(){

               ArrayList<OccupationCode> occuCodeList=new ArrayList<OccupationCode>();

               OccupationCode programmer=new OccupationCode();
               programmer.setOccupationId(new Integer(3));
               programmer.setOccupationDescription("Computer Programmer");
               occuCodeList.add(programmer);


               return occuCodeList;
       }
}

But it is throwing an error like below...

unexpected invocation: iOccupationCodeDAO.getOccupationCodes()
no expectations specified: did you...
 - forget to start an expectation with a cardinality clause?
 - call a mocked method to specify the parameter of an expectation?
what happened before this: nothing!
       at
org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:56)
       at org.jmock.Mockery.dispatch(Mockery.java:218)
       at org.jmock.Mockery.access$000(Mockery.java:43)
       at org.jmock.Mockery$MockObject.invoke(Mockery.java:258)
       at org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
       at org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
       at
org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
       at $Proxy3.getOccupationCodes(Unknown Source)
       at
com.sumobrain.api.business.service.SampleTest$1.<init>(SampleTest.java:47)
       at
com.sumobrain.api.business.service.SampleTest.testGetLookupDataForRegistration(SampleTest.java:46)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
       at java.lang.reflect.Method.invoke(Unknown Source)
       at junit.framework.TestCase.runTest(TestCase.java:168)
       at junit.framework.TestCase.runBare(TestCase.java:134)
       at junit.framework.TestResult$1.protect(TestResult.java:110)
       at junit.framework.TestResult.runProtected(TestResult.java:128)
       at junit.framework.TestResult.run(TestResult.java:113)
       at junit.framework.TestCase.run(TestCase.java:124)
       at junit.framework.TestSuite.runTest(TestSuite.java:232)
       at junit.framework.TestSuite.run(TestSuite.java:227)
       at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
       at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
       at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
       at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)

Any Help is really appreciated.

Thanks:working:
--
View this message in context: http://www.nabble.com/Testing-a-method-taking-no-input-parameters-tp20444371p20444371.html
Sent from the jMock - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

   http://xircles.codehaus.org/manage_email




Dayal | 11 Nov 19:49 2008
Picon

Re: Testing a method taking no input parameters


How to mock a method???? 

I have done one example in similar fashion. But has only one DAO in the
object. It did work fine. 
 if you provide any exampes, that would be great.

ravisankarvivek wrote:
> 
> Check whether all methods are mocked...each and every one..that is the
> problem..
> 
> -viv
> On Tue, Nov 11, 2008 at 11:02 PM, Redmund reynolds
> <dayal_407@...>wrote:
> 
>>
>> Hi,
>>
>> I am new to JMock. I am using version 2.5. I tried one example with JMock
>> and it worked fine. Then I tried to implement it in our project, but
>> ruuning
>> into problems. Here is the situation.
>>
>> I have service class like this
>>
>> public class UserManagementServicesImpl implements IUserManagementService
>> {
>>
>>        public UserManagementServicesImpl(){
>>                super();
>>        }
>>
>>        private IOccupationCodeDAO occuCodeDAO;
>>        private ICountryCodeDAO countryCodeDAO;
>>        private IDegreeCodeDAO degreeCodeDAO;
>>        private IIndustryTypeCodeDAO industryCodeDAO;
>>
>>        public LookupCodesVo getLookupDataForRegistration() throws
>> APIUserServicesException{
>>                logger.debug("Begin
>> UserManagementServicesImpl::getLookupDataForRegistration");
>>                LookupCodesVo lookupCodesVo=null;
>>                try{
>>                        lookupCodesVo=new LookupCodesVo();
>>
>>  lookupCodesVo.setOccuCodes(occuCodeDAO.getOccupationCodes());
>>
>>  lookupCodesVo.setCountryCodes(countryCodeDAO.getCountryCodes());
>>
>>  lookupCodesVo.setDegreeCodes(degreeCodeDAO.getDegreeCodes());
>>
>>  lookupCodesVo.setIndustryCodes(industryCodeDAO.getIndustryTypeCodes());
>>                } catch (APIUserServicesException exp) {
>>                        logger.error("Exception
>>
>> UserManagementServicesImpl:getLookupDataForRegistration::"+exp.getMessage());
>>                        exp.printStackTrace();
>>                        throw exp;
>>                }catch (Exception e) {
>>                        logger.error("Exception
>> UserManagementServicesImpl:getLookupDataForRegistration::"+e.getMessage());
>>                        e.printStackTrace();
>>                        throw new
>>
>> APIUserServicesException("Exception",e.getMessage(),"getLookupDataForRegistration",e.getClass().getName()
>> );
>>                }
>>                logger.debug("End
>> UserManagementServicesImpl::getLookupDataForRegistration");
>>                return lookupCodesVo;
>>        }
>>
>> ............. and setters for DAOs
>>
>> I have unit test case like below
>>
>> public class UserRegistrationTest extends UserMngmtServiceTest {
>>
>>        public UserRegistrationTest(){
>>                countryCodeDAO=context.mock(ICountryCodeDAO.class);
>>                degreeCodeDAO=context.mock(IDegreeCodeDAO.class);
>>                industryCodeDAO=context.mock(IIndustryTypeCodeDAO.class);
>>                occuCodeDAO=context.mock(IOccupationCodeDAO.class);
>>
>>                userMngmtServie.setCountryCodeDAO(countryCodeDAO);
>>                userMngmtServie.setDegreeCodeDAO(degreeCodeDAO);
>>                userMngmtServie.setIndustryCodeDAO(industryCodeDAO);
>>                userMngmtServie.setOccuCodeDAO(occuCodeDAO);
>>        }
>>
>>        public void testGetLookupDataForRegistration(){
>>                try{
>>                        context.checking(new Expectations(){{
>>                                oneOf(occuCodeDAO.getOccupationCodes());
>>
>>  will(returnEnumeration(preparOccupationCodes()));
>>
>>                                oneOf(countryCodeDAO.getCountryCodes());
>>
>>  will(returnEnumeration(preparCountryCodes()));
>>
>>                                oneOf(degreeCodeDAO.getDegreeCodes());
>>
>>  will(returnEnumeration(preparDegreeCodes()));
>>
>>
>>  oneOf(industryCodeDAO.getIndustryTypeCodes());
>>
>>  will(returnEnumeration(preparIndustryCodes()));
>>                        }});
>>
>>                        LookupCodesVo
>> lookupCodesVo=userMngmtServie.getLookupDataForRegistration();
>>                        context.assertIsSatisfied();
>>
>>                }catch (Exception e) {
>>                        e.printStackTrace();
>>                }
>>        }
>>
>>        private ArrayList<CountryCode> preparCountryCodes(){
>>
>>                ArrayList<CountryCode> countryCodeList=new
>> ArrayList<CountryCode>();
>>
>>                CountryCode usa=new CountryCode();
>>                usa.setCountryId(new Integer(1));
>>                usa.setCountryName("United States Of America");
>>                countryCodeList.add(usa);
>>
>>                CountryCode uk=new CountryCode();
>>                uk.setCountryId(new Integer(2));
>>                uk.setCountryName("United Kingdom");
>>                countryCodeList.add(uk);
>>
>>                return countryCodeList;
>>        }
>>
>>        private ArrayList<DegreeCode> preparDegreeCodes(){
>>
>>                ArrayList<DegreeCode> degreeCodeList=new
>> ArrayList<DegreeCode>();
>>
>>                DegreeCode bs=new DegreeCode();
>>                bs.setDegreeTypeId(new Integer(1));
>>                bs.setDegreeTypeDesc("Bachelors in Science");
>>                degreeCodeList.add(bs);
>>
>>                DegreeCode ms=new DegreeCode();
>>                ms.setDegreeTypeId(new Integer(2));
>>                ms.setDegreeTypeDesc("Masters in Science");
>>                degreeCodeList.add(ms);
>>
>>                return degreeCodeList;
>>        }
>>
>>        private ArrayList<IndustryTypeCode> preparIndustryCodes(){
>>
>>                ArrayList<IndustryTypeCode> industryCodeList=new
>> ArrayList<IndustryTypeCode>();
>>
>>                IndustryTypeCode it=new IndustryTypeCode();
>>                it.setIndustryTypeId(new Integer(1));
>>                it.setIndustryTypeDesc("Information Technology");
>>                industryCodeList.add(it);
>>
>>                IndustryTypeCode acct=new IndustryTypeCode();
>>                acct.setIndustryTypeId(new Integer(4));
>>                acct.setIndustryTypeDesc("Accounting");
>>                industryCodeList.add(acct);
>>
>>
>>                return industryCodeList;
>>        }
>>
>>        private ArrayList<OccupationCode> preparOccupationCodes(){
>>
>>                ArrayList<OccupationCode> occuCodeList=new
>> ArrayList<OccupationCode>();
>>
>>                OccupationCode programmer=new OccupationCode();
>>                programmer.setOccupationId(new Integer(3));
>>                programmer.setOccupationDescription("Computer
>> Programmer");
>>                occuCodeList.add(programmer);
>>
>>
>>                return occuCodeList;
>>        }
>> }
>>
>> But it is throwing an error like below...
>>
>> unexpected invocation: iOccupationCodeDAO.getOccupationCodes()
>> no expectations specified: did you...
>>  - forget to start an expectation with a cardinality clause?
>>  - call a mocked method to specify the parameter of an expectation?
>> what happened before this: nothing!
>>        at
>>
>> org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:56)
>>        at org.jmock.Mockery.dispatch(Mockery.java:218)
>>        at org.jmock.Mockery.access$000(Mockery.java:43)
>>        at org.jmock.Mockery$MockObject.invoke(Mockery.java:258)
>>        at
>> org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
>>        at
>> org.jmock.internal.FakeObjectMethods.invoke(FakeObjectMethods.java:38)
>>        at
>>
>> org.jmock.lib.JavaReflectionImposteriser$1.invoke(JavaReflectionImposteriser.java:33)
>>        at $Proxy3.getOccupationCodes(Unknown Source)
>>        at
>> com.sumobrain.api.business.service.SampleTest$1.<init>(SampleTest.java:47)
>>        at
>>
>> com.sumobrain.api.business.service.SampleTest.testGetLookupDataForRegistration(SampleTest.java:46)
>>        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
>>        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
>>        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
>>        at java.lang.reflect.Method.invoke(Unknown Source)
>>        at junit.framework.TestCase.runTest(TestCase.java:168)
>>        at junit.framework.TestCase.runBare(TestCase.java:134)
>>        at junit.framework.TestResult$1.protect(TestResult.java:110)
>>        at junit.framework.TestResult.runProtected(TestResult.java:128)
>>        at junit.framework.TestResult.run(TestResult.java:113)
>>        at junit.framework.TestCase.run(TestCase.java:124)
>>        at junit.framework.TestSuite.runTest(TestSuite.java:232)
>>        at junit.framework.TestSuite.run(TestSuite.java:227)
>>        at
>>
>> org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
>>        at
>>
>> org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
>>        at
>>
>> org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
>>        at
>>
>> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
>>        at
>>
>> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
>>        at
>>
>> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
>>        at
>>
>> org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
>>
>> Any Help is really appreciated.
>>
>> Thanks:working:
>> --
>> View this message in context:
>> http://www.nabble.com/Testing-a-method-taking-no-input-parameters-tp20444371p20444371.html
>> Sent from the jMock - User mailing list archive at Nabble.com.
>>
>>
>> ---------------------------------------------------------------------
>> To unsubscribe from this list, please visit:
>>
>>    http://xircles.codehaus.org/manage_email
>>
>>
>>
> 
> 

--

-- 
View this message in context: http://www.nabble.com/Testing-a-method-taking-no-input-parameters-tp20444371p20445847.html
Sent from the jMock - User mailing list archive at Nabble.com.

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


Gmane