Mock question?

Hi all

Not sure if this is the right group, I am happyo to repost to correct
group if I know what that is! but in the mean time - here goes

I am using NMock2 and I have question.

I have the following interface:

    public interface ITime
    {
        int Hour { get; }
    }

and the following weather service:

    public class WeatherService:ITime
    {
        public string GetTodaysWeather()
        {
            if (Hour >= 0 && Hour <= 6)
            {
                return "Sunny";
            }
            else if (Hour >= 7 && Hour <= 15)
            {
                return "Foggy";
            }
            else
            {
                return "Snowing";
            }
        }

        public int Hour
        {
            get { return DateTime.Now.Hour; }
        }
    }

In order for me to test this I have created the simple test:

     [Test]
        public void CanGetSunnyWeather()
        {
            Mockery m = new Mockery();
            ITime mockObject = m.NewMock<ITime>();

 
Stub.On(mockObject).GetProperty("Hour").Will(Return.Value(2));

            WeatherService ws = new WeatherService();
            Assert.AreEqual("Sunny", ws.GetTodaysWeather());
            m.VerifyAllExpectationsHaveBeenMet();
        }

This fails as the Hour Property on Weather service doesnt get mocked
and I expected it to. Why is this? I want to be able to test this
weather servce without relying on the time which is why I mocked it -
but it doesnt behave as expected any ideas anyone?
0
Ilyas
4/2/2010 3:55:34 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

3 Replies
943 Views

Similar Articles

[PageSpeed] 7

Hi,

As this is related to a particular library, it's likely best to use :
http://sourceforge.net/projects/nmock2/support

Don't know how it works but what if you mock the class rather than the 
interface ? Keep in mind that the interface doesn't provide any 
implementation.

--
Patrice 

0
Patrice
4/2/2010 7:10:17 PM
Hi

maybe I'll not answer your question. But in the end you might still end 
up with a solution.

In my opinion you should create a class TimeProvider that implements 
your interface ITime. You then add an instance to your WeatherService.

You also want to provide a setter for the timeProvider. You might also 
want to provide a Constructor WeatherService(ITime timeProvider) to set 
the timeProvider at construction time.

You can then use either a fake implementation FakeTimeProvider, which 
always returns 2 for the hour, that is added to your WeatherService or 
you can use NMock to mock this TimeProvider.

Hope this helps

Al.

ps: untested code

public interface ITime
{
	int Hour { get; }
}

public class TimeProvider : ITime
{
	public int Hour
	{
		get { return DateTime.Now.Hour; }
	}
}

public class WeatherService
{
	ITime timeProvider;

	// --- provide a setter if you want to change timeProvider
	//     after construction

	WeatherService(ITime timeProvider)
	{
		this.timeprovider = timeProvider;
	}

	public string GetTodaysWeather()
         {
		// you get the idea
	}
}


On 02.04.2010 17:55, Ilyas wrote:
> Hi all
>
> Not sure if this is the right group, I am happyo to repost to correct
> group if I know what that is! but in the mean time - here goes
>
> I am using NMock2 and I have question.
>
> I have the following interface:
>
>      public interface ITime
>      {
>          int Hour { get; }
>      }
>
> and the following weather service:
>
>      public class WeatherService:ITime
>      {
>          public string GetTodaysWeather()
>          {
>              if (Hour>= 0&&  Hour<= 6)
>              {
>                  return "Sunny";
>              }
>              else if (Hour>= 7&&  Hour<= 15)
>              {
>                  return "Foggy";
>              }
>              else
>              {
>                  return "Snowing";
>              }
>          }
>
>          public int Hour
>          {
>              get { return DateTime.Now.Hour; }
>          }
>      }
>
> In order for me to test this I have created the simple test:
>
>       [Test]
>          public void CanGetSunnyWeather()
>          {
>              Mockery m = new Mockery();
>              ITime mockObject = m.NewMock<ITime>();
>
>
> Stub.On(mockObject).GetProperty("Hour").Will(Return.Value(2));
>
>              WeatherService ws = new WeatherService();
>              Assert.AreEqual("Sunny", ws.GetTodaysWeather());
>              m.VerifyAllExpectationsHaveBeenMet();
>          }
>
> This fails as the Hour Property on Weather service doesnt get mocked
> and I expected it to. Why is this? I want to be able to test this
> weather servce without relying on the time which is why I mocked it -
> but it doesnt behave as expected any ideas anyone?

0
Alberto
4/4/2010 6:12:27 PM
hi

to answer your question. Your mock is actually never called. Use my 
earlier advice to fix it

Al.
0
Alberto
4/4/2010 6:52:44 PM
Reply:

Similar Artilces:

Time Conversion question
One of the pieces of software we use gives us time in an awkward format. 16633 means 166 minutes 33 seconds. I need a formula to convert this figure to a decimal respresentation of time (166.55 for the example listed previously). Any help will be much appreciated. =INT(A1/100)+MOD(A1,100)*5/300 HTH. Best wishes Harald "Sean Skallerud" <SeanSkallerud@discussions.microsoft.com> skrev i melding news:050BD3C6-E67A-4F94-B08B-695A038B33A6@microsoft.com... > One of the pieces of software we use gives us time in an awkward format. > 16633 means 166 minutes 33 seconds. I...

RTV Questions
I noticed that I can enter many items on an RTV transaction. When I go to the RTB Shipping window and check mark the M column on one of the items, it asks if I want all items for that RTV transaction marked. Do you need to enter the cost for each item? If I mark all items on the RTV transaction and hit the Post button, many payables credit memos are created. Will it create many payables credit memos or is there a setting to create only one credit memo? >I noticed that I can enter many items on an RTV transaction. When I go to the RTB Shipping window and check mark the M column on...

XSL If Question
Hi, I am using XSL if to look and see if a node exists and if so display it with a header (see below). Some of the xml I transforming has nodes like this <Test /> and it shows up in my html report (header no value). How do I test for this? <xsl:if test="Test"> <xsl:if test="Test"> <b><xsl:text>Header: </xsl:text></b> <xsl:value-of select="Test"/> <br></br> </xsl:if> Thanks test for: Test[normalize-space(node())] Cheers, Dimitre Novatchev "Fred" <fred@fred.com> wrote...

Question about installing the CRM-Exchange E-mail Router on Exchange server with Mail Essentials anti-spammer installed
Getting ready to install the CRM-Exchange e-mail router on my Exchange 2000 Server. We also happen to have the Mail Essentials Anti-Spam software installed on this exchange server. Does anyone know of any negative interactions or anything I need to be aware of before installing the E-mail router? Thanks for the response! -Dave Vandenberghe dave@global-image.com We too are using third-party anti-spam software on our Exchange 2K server and it hasn't had any conflict with the Email Router for CRM. -Gary "Dave Vandenberghe" <dave@global-image.com> wrote in message ne...

General Novice Questions (Protection, Format)
I have created a spreadsheet and have restricted a row and footing row (totals) from being changed by using the "format cells / protection" feature. I have left all the data entry rows unprotected so that the entry people can make changes. These entry rows have columns with specfics formats like Date, Currency, etc and I make it all look nice with the grid feature. Finally, I set "Tools /Protection/ Protect sheet" to active the protected cells. The problem is how can the user Insert new rows? To get around this, I created enough rows so that the user has the space they n...

Outlook question #8
I'm using Microsoft Outlook 2007 and am having trouble setting my email up correctly. I am unable to see animations and hear music within an email. Outlook Express had this capability, but doesn't Outlook, it seems to be a superior product from OE. MS <MS@discussions.microsoft.com> wrote: > I'm using Microsoft Outlook 2007 and am having trouble setting my > email up correctly. I am unable to see animations and hear music > within an email. Outlook Express had this capability, but doesn't > Outlook, it seems to be a superior product from OE. For securi...

Question???
I have a spreadsheet with calculations I also have a website and I wa wondering is there a way to cut out a section of an excel spreadshee to just show that on my webpage or will I have to have the whole exce page open to get my calculations to work. Basically I want a little bo on my webpage with the small spreadsheet but I don't want to have t open the whole page. Not sure If I explained that well enough...lo -- CadensDa ----------------------------------------------------------------------- CadensDad's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=1746 Vi...

Simple Report Formatting Question
Good morning everyone. I have what I think is a fairly simple question, with hopefully a simple answer. Question is regarding the "Can Grow" property. The fields in the DETAILS section of my report contain borders. I have the CAN GROW property set to Yes for all fields. My question is - if one of the fields needs to grow to accomodate text data, how can instruct the remaining fileds to also grow to the same size. The right most field in my report contains user comments (it is a memo field), and quite often it needs to grow, but the remaining fields in the row do not grow. The r...

SUMIF question #3
Hi, I have a workbook with column A formatted as dates, and column B containing numbers. I would like to know how to get excel to tell me how much the sum of the numbers would be for a given time frame. So, for instance, if I wanted to know the sum of the numbers in column B that have year 2006 in column A, etc. There must be a way to do this, but I'm stumped. Also, can the criteria in the date be narrowed to give me a sum of just, say, a given month within a given year? Thanks in advance, Jim Try this: With Dates in A1:A30 Amounts in B1:B30 Here are 2 variations of the same formu...

Question
I have a typical office network configured under windows 2003 server. If the shared folders stored on the server suddenly start getting disconnected from each terminal, that means that my DNS on each terminal has been wrongly configured, or there is another thing to consider? Thanks JPG Can you post unedited ipconfig /all from server and client? -- Regards, Dave Patrick ....Please no email replies - reply in newsgroup. Microsoft Certified Professional Microsoft MVP [Windows] http://www.microsoft.com/protect "Juan Pablo Gallardo" wrote: >I h...

Public Folders migration question
Hi there, I've just finished migrating all our mailboxes & public folders to a new Exchange 2k3 server (from Exch 2k). I've followed the steps in 307917 to remove the first exchange server from the site. I'd set the new server as a replication partner for all public folders (incl. system folders: Offline Address Book, OAB Version 2, Schedule+, & Internet Newsgroups), allowed for full replication to occur. I rehomed RUS & designated the new server as routing group master. Yesterday, I turned off all services on the old mail server. Today, the queue (queue name: OLD...

Excel Spreadsheets Reformat Question
I have a disk full of Excel files; I suspect they were created by exporting from an accounting program to Excel to share the financial information with others. Each of these files needs to be PDFd and Bates stamped for production in a legal matter. The problem is this: every single one of these Excel files is not formatted to display all of the information - in order to get a readable page, the columns need to be reformatted to display all of the information contained in each of them, then saved. There are literally hundreds of these files; would there be an easier way of gett...

Printing question
This is a very general question so I might miss something here but this is more of help direction than anything. I need to develop a web app (may be create a silverlight client) which reads bunch of xml and associate them appropriate XSLT and allow users to print them. What is the best way to go about doing it? Thanks, CSharper wrote: > This is a very general question so I might miss something here but > this is more of help direction than anything. > > I need to develop a web app (may be create a silverlight client) which > reads bunch of xml and associate t...

My question gets deleted
Why is my question gets deleted ? I posted twice and it got deleted twice.... I'm getting mad... who has the authority to delete posts in this group ? Julien, Your posts are there. Are you sure your newsgroup reader is not set to hide postes that have already been viewed? Marc "Julien Bonnier" <julien@m0851.com> wrote in message news:OdGmzENGJHA.1272@TK2MSFTNGP02.phx.gbl... > Why is my question gets deleted ? > > > I posted twice and it got deleted twice.... I'm getting mad... who has the > authority to delete posts in this group ? > ...

doc/view question #3
I have a doc/view exe that I created as Explorer-style, which means that each doc has a splitter window like windows Explorer. When the user moves the splitter position, I want the doc to be able to save this info, and restore it when the doc is reopened. How can I accomplish this, since the splitter lives in the ChildFrm rather than a view? Also, how can I create MDI child windows maximized? As the help suggests, in CChildFrm I overrode the PreCreateWindow method to add the WS_MAXIMIZE style, but this didn't work. Lastly, how can I maximize the application itself? Thanks for t...

general question re jpg files
I have no problem opening jpg files when they reside in an e-mail message or even in a folder in 'Computer'. My problem is this, when I go to open a jpg file on my Desktop, nothing happens until I right click and 'Open with' and then make a choice. What don't I understand here. I'm running Vista Home Premium, SP2 and up to date with the lastest WU. Thanks, Dave Horne "Dave Horne" <davehorne@home.nl> wrote: >I have no problem opening jpg files when they reside in an e-mail message or >even in a folder in 'Computer'. My pr...

Publisher question
Can I change a Publisher file to a .jpg or .tif format? How? sally <sally@discussions.microsoft.com> was very recently heard to utter: > Can I change a Publisher file to a .jpg or .tif format? How? Publisher 2002 and 2003 you can go to File > Save As and select TIFF or JPEG format. Publisher 2000 or earlier you will need a third-party app like FinePrint (www.fineprint.com) or SnagIt (www.techsmith.com) -- Ed Bennett - MVP Microsoft Publisher "Ed Bennett" wrote: > sally <sally@discussions.microsoft.com> was very recently heard to > utter: > &...

Basic questions
Hello, I have never seen or used Windows Server and I have a few basic questions before switching Windows XP Pro into WS 2008 R2. Will I be able to install and use other softwares normally as if I was using Windows XP? I have other servers I would like to use with it and I need to know in advance if they will be 100% compatible: Oracle XE 10g MySQL (latest version) Apache 2.2 FileZilla server Windows Media Player 12 sharing Ultra VNC So, please let me know if the above software would be OK and besides that, I would have to test some programs I develop by myself, so I ne...

ActiveCell.Offset Question
Hi, Spreadsheet with many columns: In All column, Row4 I have dates: What I like to do is: "IF" I am in Column y "Any row" I would like to go up to Y4 and copy that value down to another cell . "IF" I am in Column de "Any row" I would like to go up to de4 and copy that value down to another cell . I wrote this thinking it may work, but I keep getting mismatch Type: Sub Look4DATE() Dim mycell As Range Set mycell = ActiveCell.Offset(0, 0) Dim myrange As Range Set myrange = Range(ActiveCell.Offset(0, 0), mycell) myc...

Mock question?
Hi all Not sure if this is the right group, I am happyo to repost to correct group if I know what that is! but in the mean time - here goes I am using NMock2 and I have question. I have the following interface: public interface ITime { int Hour { get; } } and the following weather service: public class WeatherService:ITime { public string GetTodaysWeather() { if (Hour >= 0 && Hour <= 6) { return "Sunny"; } else if (Hour >= 7 &&...

Exchange 2003 Question??
Dear all, I would like to know if there is an upgrade path from Exchange 2003 Standard Edition with SA to Exchange 2003 Enterprise Edition with SA? Thank you. Regards, Kueh. This might help http://support.microsoft.com/default.aspx?scid=kb;en-us;170280 -- Santhosh Sivarajan MCSE(W2K/NT4),MCSA(W2K3/W2K/MSG),CCNA,Network+ "KA Kueh" <kka@ksm.com.my> wrote in message news:exVKwgOKEHA.1040@TK2MSFTNGP10.phx.gbl... > Dear all, > > I would like to know if there is an upgrade path from Exchange 2003 Standard > Edition with SA to Exchange 2003 Enterprise Edition wit...

Formula Question... LookUP
I am using the follwing formula to calculate the last entry in a range.. =LOOKUP(1,1/(1-ISBLANK('04&05 Details'!C416:C428)),'04&05 Details'!C416:C428) Is there a simple way to calculate the last but one ??? Any help greatly appreciated.. Thanks G, rephrase your question. I'm not sure what you mean by this. Are you trying to calculate its position on the worksheet? O -- Message posted via http://www.officekb.com Hi! >Is there a simple way to calculate the last but one ??? Does that mean if your formula returns the value in C420 you now want a formula ...

CBitmapButton Question.
I'm trying to add a bitmap button on a SDI application (in winCE). I follows the steps in msdn but not works: 1)Create one to four bitmap images for the button. I created them , attached to resource editor.Name them properly.The fist bitmap ID is IDB_BITMAP1; 2)Construct the CBitmapButton object. CBitmapButton *pButton = new CBitmapButton(); 3)Call the Create function to create the Windows button control CButton myButton1; myButton1.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON, CRect(10,10,100,30), pParentWnd, 1); 4)and attach it to the CBitmapButton object. ...

Address question
Ok, I've got a function that returns the address of the cell. Usin that address (say $D$306), I need to check for the first empty cell i Cells(D307:D321). Any suggestions -- Message posted from http://www.ExcelForum.com Hi do you need a worksheet function or some VBA code. For a worksheetfunction you may use the following to return the row number of your first blank cell (enter this formula as array formula with CTRL+SHIFT+ENTER): =306+MATCH(TRUE,ISBLANK(D307:D321),0) >-----Original Message----- >Ok, I've got a function that returns the address of the cell. Using >t...

Question about Paste Special
Hi, I have a problem sometimes with the paste special options when goin from one excel workbook to another. For example, sometimes when I cop data from one workbook and then paste special into another, I get th options that include: All, formulas, values, formats, has the option t transpose the data and paste link among other options. And the sometimes I try and paste data to another workbook and I end up th paste special options: Bitmap Image Object, picture, bitmap, and I als lose the ability to paste link. Well you can do it, but it puts it i as an object. What I want is the first past...