I have an BLL that does validation on user input then inserts a parent(PorEO) and then inserts children(PorBoxEO). So there are two calls to the same InsertJCDC. One like this=>InsertJCDC(fakePor) and another like this=>InsertJCDC(fakeBox).
When I stub out the parent I want to return fakePor. But when I run the code it returns null instead. Here is the unit test.
[Test]
public void PorBLL_InsertByPorInsertCV_DoingGoodCase()
{
// Startup object mapper
_Bootstrapper.Bootstrap();
// create the mock for generic Crud
IGenericCrud mockGenericCrud = MockRepository.GenerateMock<IGenericCrud>();
PorInsertCV fakePor = new PorInsertCV();
PorBoxInsertCV fakeBox = new PorBoxInsertCV();
// build fake return
PorEO fakePorNewRow = new PorEO();
fakePorNewRow.PorId = 22;
// stub parent and child insert routines.
mockGenericCrud.Stub(c => c.InsertJCDC<PorEO, PorInsertCV>(fakePor)).Return(fakePorNewRow);
mockGenericCrud.Stub(c => c.InsertJCDC<PorBoxEO, PorBoxInsertCV>(fakeBox)).Return(null);
ObjectFactory.Inject(typeof(IGenericCrud), mockGenericCrud);
IPorBLL localWithMock = ObjectFactory.GetInstance<IPorBLL>();
// build user args to csll bll with and use for insert
PorInsertCV userArgs = new PorInsertCV();
userArgs.AccessionNbr = "364-80-0007";
userArgs.NbrBoxes = 11;
userArgs.RegId = 20;
userArgs.TransmitedDt = Convert.ToDateTime("1/30/1980");
// call the bll using the stub
localWithMock.InsertByPorInsertCV(userArgs);
}
Any help is greatly appreciated
I can't really follow your code that well, but I'll give it a shot.
From my skills of deduction, this line here is the one giving you issues:
mockGenericCrud.Stub(c => c.InsertJCDC<PorEO, PorInsertCV>(fakePor)).Return(fakePorNewRow);
Because you're expecting fakePorNewRow to be returned when you call localWithMock.InsertByPorInsertCV(userArgs); - yeah?
If that's your case, what your problem is, is that it will only return fakePorNewRow when it is given fakePor ... not userArgs as you have given it.
Tell me if I'm completely off track.
HTHs,
Charles
Ps. You might want to add the tag of which mocking framework you are using to the question.
Related
I'm looking to see if it's at all possible to specify a Times enum value in the setup of a mocked property that can then be exercised by the MockRepository.Verify() method at the Assert block of my AAA-style test. My current code reads like so:
// Arrange
var repository = new MockRepository(MockBehavior.Default);
var mockLogin = repository.Create<Login>();
mockLogin.SetupProperty(d => d.LoginID, 1515254);
var mockIApplicationEventLogService = repository.Create<IApplicationEventLogService>();
mockIApplicationEventLogService.Setup(d => d.InsertApplicationEventLog(It.IsAny<ApplicationEventLog>())).Verifiable();
var mockILoginResetFailedService = repository.Create<ILoginResetFailedService>();
mockILoginResetFailedService.Setup(d => d.GetLoginResetFailedByLoginID(It.IsAny<int>())).Returns((LoginResetFailed)null);
var mockApplicationEventLog = repository.Create<ApplicationEventLog>();
mockApplicationEventLog.SetupAllProperties();
var LoginWorkflowService = new LoginWorkflowService()
{
ApplicationEventLogService = mockIApplicationEventLogService.Object,
ApplicationEventLog = mockApplicationEventLog.Object,
LoginResetFailedService = mockILoginResetFailedService.Object
};
// Act
var result = LoginWorkflowService.CheckLoginResetFailuresLock(mockLogin.Object, It.IsAny<Guid>(), It.IsAny<SecurityPolicy_Aggregate>(), It.IsAny<string>(), It.IsAny<string>());
// Assert
result.Should().BeTrue();
mockIApplicationEventLogService.Verify(d => d.InsertApplicationEventLog(It.IsAny<ApplicationEventLog>()), Times.Never);
What I'd like to be able to do is call repository.Verify() at the end, but with my current code the Verify() call will expect InsertApplicationEventLog to have been called when in fact I expect it to never have been called. I have tried passing Times.Never into the Setup method for mockIApplicationEventLogService but it doesn't seem that there's a method override that takes it. Am I limited to individual Verify() calls if I have mocks in my repository that should never be called, or is there a way around this?
It appears as Nkosi said, it's not currently possible to do this. There is a request for this at the following URL:
https://github.com/moq/moq4/issues/373
I have a bunch of WebPartBase classes that I'm trying to invoke a method on. Some of the methods call controls on the UI. I want to stub out those controls somehow so that an exception doesn't get thrown when attempting to set values on them. Does anyone know of a good way to do this? It would also be fine if they were initialized but I'm not sure how to initialize them without running a web server.
My test code looks like this. IntializeOnAdd() is a method on KPIWebPartBase and KPIWebPartBase inherits from WebPartBase.
[TestMethod]
public void InvokeAllWidgets()
{
var user = new User("adminqaphi");
user.CustomerID = TestConfig.ClientID;
var classes = typeof(KPIWebPartBase)
.Assembly
.GetTypes()
.Where(t => t.IsSubclassOf(typeof(KPIWebPartBase)) && !t.IsAbstract );
foreach (var c in classes)
{
Console.WriteLine(c.Name);
var instance = (KPIWebPartBase)Activator.CreateInstance(c);
foreach (var billingMetric in Enum.GetValues(typeof(BillingMetric)))
{
instance.CurrentUser = user;
instance.BillingMetric = (BillingMetric)billingMetric;
if (instance is StartEndKPIWebPartBase)
{
var startEndKPI = (StartEndKPIWebPartBase)instance;
startEndKPI.StartDate = new DateTime(2007, 1, 1);
startEndKPI.EndDate = new DateTime(2008, 1, 1);
}
instance.InitializeOnAdd();
}
}
}
I would create interfaces for them (if possible) and use moq to create Mocks or stubs for the external dependencies.
What behavior does InvokeAllWidgets() test?
Response to comment:
I think you should mock the database as well, so that you just test the "internal" logic of the code(unit). Otherwise you will en up testing the database, and I guess that is not what you want to. And if you do call the database, what happens if some data in it changes? Will that fail your tests? If so I think you are doing integration tests and not unit tests. In a unit test try to mock all external dependencies and test your own logic (what can go wrong?). If your code don't allow you test it like, then change it!
Hey folks, i ve got this issue implementing the Factory method.
Following is the snippet of the the main chart class which calls ChartFactory's method to attain the proper object. I Type Cast chartobject so as to be able to call the Show method;i m apprehensive about that as well.
container = new VBox();
container.percentWidth = 100;
container.percentHeight = 100;
super.media.addChild(container);
chartObject = new ChartBase();
chartObject = ChartFactory.CreateChartObject(chartType);
IChart(chartObject).Show(o);
container.addChild(chartObject);
legend = new Legend();
legend.dataProvider = IChart(chartObject);
container.addChild(legend);
Following is the snippet of ChartFactory's method:
public static function CreateChartObject(subType:String):ChartBase
{
switch(subType)
{
case ChartFactory.AREA_CHART:
return new AreaCharts();
break;
case ChartFactory.COLUMN_CHART:
return new ColumnCharts();
break;
case ChartFactory.PIE_CHART:
return new PieCharts();
break;
default:
throw new ArgumentError(subType + ": Chart type is not recognized.");
}
}
And following is Show method of one of the several Charts type classes: AreaCharts, PieCharts etc. All of which implements IChart Interface.
public function Show(o:ObjectProxy):void
{
var grids:GridLines;
var stroke:SolidColorStroke;
var horizontalAxis:CategoryAxis;
var verticalAxis:LinearAxis;
var horizontalAxisRenderer:AxisRenderer;
var verticalAxisRenderer:AxisRenderer;
grids = new GridLines();
if(WidgetStylesheet.instance.LineChart_ShowGrid)
grids.setStyle("gridDirection", "both");
else
grids.setStyle("gridDirection", "");
stroke = new SolidColorStroke(WidgetStylesheet.instance.LineChart_GridLineColor, WidgetStylesheet.instance.LineChart_GridLineThickness);
grids.setStyle("horizontalStroke", stroke);
grids.setStyle("verticalStroke", stroke);
horizontalAxis = new CategoryAxis();
horizontalAxis.categoryField = o.LargeUrl.Chart.xField;
horizontalAxis.title = o.LargeUrl.Chart.xAxisTitle.toString();
verticalAxis = new LinearAxis();
verticalAxis.title = o.LargeUrl.Chart.yAxisTitle.toString();
horizontalAxisRenderer = new AxisRenderer();
horizontalAxisRenderer.axis = horizontalAxis;
horizontalAxisRenderer.setStyle("tickLength", 0);
horizontalAxisRenderer.setStyle("showLine", false);
horizontalAxisRenderer.setStyle("showLabels", true);
horizontalAxisRenderer.setStyle("fontSize", WidgetStylesheet.instance.ComputeChartAxisFontSize(o.HeadlineFontSize));
verticalAxisRenderer = new AxisRenderer();
verticalAxisRenderer.axis = verticalAxis;
verticalAxisRenderer.setStyle("tickLength", 0);
verticalAxisRenderer.setStyle("showLine", false);
verticalAxisRenderer.setStyle("fontSize", WidgetStylesheet.instance.ComputeChartAxisFontSize(o.HeadlineFontSize));
this.series = this.m_createSeries(o);
this.horizontalAxis = horizontalAxis;
this.horizontalAxisRenderers = [horizontalAxisRenderer];
this.verticalAxis = verticalAxis;
this.verticalAxisRenderers = [verticalAxisRenderer];
this.backgroundElements = [grids];
}
I'm afraid that there is more than one issue with this code. Unfortunately it is not obvious why your chart doesn't show up so you may apply some of advices below and use debugger to analyse the issue.
There is no point in creating ChartBase instance if you are going to change value of chartObject reference in the next line
chartObject = new ChartBase();
chartObject = ChartFactory.CreateChartObject(chartType);
If the API of your charts is IChart your factory should return IChart instead of casting.
public static function CreateChartObject(subType:String):IChart
Make sure that you are returning instances of the correct class from the factory. i.e. that you are returning your subclass of standard PieChart. Generally it's not the best idea to extend the class keeping the same name and just changing the package.
Once again, if you are not sure if the program enters some function use the Flash Builder debugger to check this. I can't imagine development without debugger.
Some thoughts:
you call the Show method, pass it some object but nowhere in that method is any child added to a displayObject. What exactly is Show supposed to do?
a lot of member variables in your classes start with UpperCase. The compiler can easily confuse those with class names, in case your classes are named the same. Bad practice to start variable and function names with capitals.
If your casting an instance to another class or interface fails, you will get a runtime error. Those are easy to debug using the Flash Builder debugger.
Hey ppl..
i found out wat wnt wrng..as olwys it wa "I".
I ve a habit of mkin mock ups secluded from the main project n dn integrate it. So in mock up i hd used an xml whch hd a format slightly diff dn d one being used in the main project.
N i hd a conditional chk to return from the prog if certain value doesnt match, n due to faulty xml i did'nt.
So this more a lexical error than a logical one.
Sorry n Thanx evryone for responding.
This is a super newbie question on Flex. While I am a seasoned programmer, this is my first ever Flex application; please bear with me for my Flex codes.
I have a web service written in ColdFusion. In this web service, there are two functions; one is to return all the questions in a quiz and the other one is to return all the answer selections to the questions in a quiz.
[Bindable]
private var questionArray:ArrayCollection;
private var cfquiz:RemoteObject;
private function loadQuestions():void {
currentQuestionCounter = 0;
btnPrev.enabled = false;
btnNext.enabled = false;
cfquiz = new RemoteObject("ColdFusion");
cfquiz.source = "CFCertExam.cfquiz";
cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
}
private function resultHandler(event:ResultEvent):void {
questionArray = event.result as ArrayCollection;
txt1Questions.htmlText = questionArray.getItemAt(currentQuestionCounter).Question_Text;
btnNext.enabled = true;
}
I have the codes above. loadQuestions is called at creationComplete to retrieve the questions. Things are working fine. What I want to do is to call another function within the same web service, returnAnswers, to return the answer options for a question. Since I have cfquiz associated to the web service already, I was using cfquiz to call returnAnswers. However, there is an event listener associated to cfquiz already, resultHandler is being called when returnAnswers comes back with the results.
My questions are, first, is it possible to check which function returns the results within resultHandler? If so, how? And second, what is the best way to handle calls to multiple functions within the same web service?
Thanks in advance,
Monte
Yes you can. You need to specify a handler function for each method which in turn calls a different webservice.
The better way to do this is using AsyncToken and AsyncResponder instead of addEventListener, as following code.
tokenA = cfquiz.methodA();
tokenA.addResponder(new AsyncResponder(onResultForMethodA, onFaultMethodA));
tokenB = cfquiz.methodA();
tokenB.addResponder(new AsyncResponder(onResultForMethodB, onFaultMethodB));
tokenC = cfquiz.methodA();
tokenC.addResponder(new AsyncResponder(onResultForMethodC, onFaultMethodC));
or
tokenA = cfquiz.methodA();
var responderA:IResponder = new AsyncResponder(onResult, onFault, "methodA");
tokenB = cfquiz.methodB();
var responderB:IResponder = new AsyncResponder(onResult, onFault, "methodB");
tokenA.addResponder(responderA);
tokenB.addResponder(responderB);
private function onResult(evt:ResultEvent, token:Object):void {
if(token == "methodA" ) {
//logic for methodA
}
if(token == "methodB" ) {
//logic for methodB
}
}
I'm a little confused as I can't see where you are calling the actual web service function, for example from these examples, I am expecting to see:
cfquiz = new RemoteObject("ColdFusion");
cfquiz.source = "CFCertExam.cfquiz";
cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
cfquiz.myCFCFunctionCall(); /* where is this? */
Anyway, AFAIK you can create a new instance of the remote object and set that up to have it's own event listener.
Hope that helps.
I am trying to build a test against some legacy method that implement out parameters.
Could you give me an example how to do this?
Just assign the out or ref parameter from the test.
Given this interface:
public interface ILegacy
{
bool Foo(out string bar);
}
You can write a test like this:
[TestMethod]
public void Test13()
{
string bar = "ploeh";
var legacyStub = new Mock<ILegacy>();
legacyStub.Setup(l => l.Foo(out bar))
.Returns(true);
Assert.IsTrue(legacyStub.Object.Foo(out bar));
Assert.AreEqual("ploeh", bar);
}
Anything wrong with the second example at the top of https://github.com/moq/moq4/wiki/Quickstart ? You really should be giving examples of what you're trying to do if you're not going to look for things like this.
Incidentally if you want to use moq (currently) to mock the out parameter too you'll also have to do the following hoop jump. Lets say that you wanted to mock an out parameter that returned another mocked object e.g.
var mockServiceA = new Mock<IMyService>();
var mockServiceOutput = new Mock<IMyServiceOutput>();
// This will not work...
mockServiceA.Setup(svc => svc.DoSomething(out mockServiceOutput.Object));
// To have this work you have to do the following
IMyServiceOutput castOutput = mockServiceOutput.Object;
mockServiceA.Setup(svc => svc.DoSomething(out castOutput));