Unit test for httppostfilebase throws an error - c#

I am using httppostfilebase in form which is present in my viewmodel as:
public HttpPostedFileBase details { get; set;}
My test is on service to repository and I want to test the Form data which is bonded with viewmodel, with fileupload. But, it throws this error:
The type initializer for 'Moq.Mock`1' threw an exception.
Below is the testing code:
public void TestMethod1()
{
var get = getservice();
VSettlement ne = new VSettlement();//vm
ne.name = " N LTD";
ne.Settle_date = new DateTime(2017, 4, 26);
ne.sAmount = 0;
ne.SPerct = 0;
ne.kCharges = 0;
ne.AAmount = 0;
ne.AmountReceived = 88500;
var file = new Mock<HttpPostedFileBase>();
file.Setup(x => x.FileName).Returns("NLTD-52.xlsx");
ne.details = file.Object;(httppostfilebase in viewmodel)
var server = new Mock<HttpServerUtilityBase>();
server.Setup(x => x.MapPath("~/trax.Tests")).Returns(#"C:\Users\Development Team\documents\visual studio 2015\Projects\trax.Tests");
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(x => x.Server).Returns(server.Object);
VReceipt pay = new VReceipt();//vm
pay.AccountID = 1032;
pay.Amount = 88500;
pay.PaymentDate=new DateTime(2017, 4, 26);
pay.PaymentModes = new SelectList("Cash");
pay.Accounts = new SelectList("CHENNAI CASH");
// act
int? s = 0;
var res= get.Add(ne, pay, 1012, out s);
Assert.IsTrue(res);
}
Please help me resolve it.

Related

Unable mock an enumerable result from a task

I want to mock the UniteofWork.FileApproveOverrideRepo.GetAllOverrideApprovals method
Everything working based on the code below just mylist is empty.
public async Task<List<FileApprovalOverrideResponse>> GetAllOverrideApprovals(int cpId)
{
var overrideApprovals = await UnitOfWork.FileApprovalOverrideRepository.Get(t => t.CPId == cpId, null, t => t.ActionedByUser.Company);
var mylist = overrideApprovals.ToList();
return MapperInstance.Map<List<FileApprovalOverrideResponse>>(mylist);
}
And here is how I mock my method :
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var mockedGenericRepoCPApproval = new Mock<IGenericAsyncRepository<FileApprovalOverride>>();
var listOfFileApprovalOverrride = new FileApprovalOverride[] {
new FileApprovalOverride()
{
FileApprovalOverrideId = 2,
FileId = 2,
CPId = 2,
ApprovalStatus = 3,
IntendedApproverType = (byte)approvType,
IsValid = true,
Reason = ""
},
new FileApprovalOverride()
{
FileApprovalOverrideId = 2,
FileId = 2,
CPId = 2,
ApprovalStatus = 3,
IntendedApproverType = (byte)approvType,
IsValid = true,
Reason = "",
}
};
var myenumerable = listOfFileApprovalOverrride;
mockedGenericRepoCPApproval.Setup(_ => _.Get(t => t.CPId == 1, null, t => t.ActionedByUser.Company)).ReturnsAsync(myenumerable);
mockedUnitOfWork.Setup(_ => _.FileApprovalOverrideRepository).Returns(mockedGenericRepoCPApproval.Object);
var cpApprovalService = new CpApprovalService(mockCPApprovalRepository.Object, new Mock<ICPRepository>().Object, new Mock<ICPService>().Object, new Mock<ICompanyRepository>().Object, new Mock<ICPLinkedCompanyService>().Object, new Mock<ICPExportService>().Object, new Mock<IEmailService>().Object, new Mock<ICPContactService>().Object, new Mock<ISystemUserRespository>().Object, new Mock<IUserManagementService>().Object, new Mock<IAuditLogService>().Object, new Mock<ISignCharterParty>().Object, new Mock<IEmailQueuer>().Object);
cpApprovalService.UnitOfWork = mockedUnitOfWork.Object;
cpApprovalService.MapperInstance = mapperInstanse;
return cpApprovalService;
I put a break point where I am creating the mock even there the myenumerable is correct and it has two members but when I run the test then the mylist is empty.

Rally Api - How do I page GetByReference results

I've got some code that looks something like this.
var userStory = restApi.GetByReference (userStoryRef, "Name", "FormattedID");
for (int i = 0; i < (int) userStory["TotalResultCount"]; i++)
{
var name = userStory["Results"][i]["Name"];
...
Of course this fails if the GetByReference has more than 20 results (i.e. TotalResultCount > 20) since the default page size is 20.
So I need to page this but I can't work out how you set the page size, or request a second page from GetByReference.
I tried adding ?pagesize=100 to the reference but it doesn't appear to affect the result set.
e.g.
var userStory = restApi.GetByReference (userStoryRef + "?pagesize=100", "Name", "FormattedID");
I also tried giving up on this altogether and re-phrasing it as a query (which I do know how to page.)
e.g.
var request = new Request("HierarchicalRequirement")
{
Fetch = new List<string>()
{
"Name", "FormattedID"
}, Query = new Query("Parent.FormattedID", Query.Operator.Equals, featureId)
};
var result = myRestApi.Query(request);
But this query doesn't work for me either (featureId is a valid formatted id with associated User Stories). But that query returns no results.
(I appreciate that's a different question altogether - happy to get either working but understanding both would be fantastic!)
Grateful as ever for any help.
See code below. Notice storiesRequest.Limit = 1000 When this number is above default 20, it defaults to max 200, so there is no need to set storiesRequest.PageSize to 200
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
using Rally.RestApi.Json;
namespace GetByRefExample
{
class Program
{
static void Main(string[] args)
{
RallyRestApi restApi = new RallyRestApi(webServiceVersion: "v2.0");
String apiKey = "_abc123";
restApi.Authenticate(apiKey, "https://rally1.rallydev.com", allowSSO: false);
String workspaceRef = "/workspace/123";
String projectRef = "/project/456";
Request request = new Request("PortfolioItem/Feature");
request.Fetch = new List<string>() { "Name", "FormattedID" };
request.Query = new Query("FormattedID", Query.Operator.Equals, "F2356");
QueryResult result = restApi.Query(request);
String featureRef = result.Results.First()._ref;
Console.WriteLine("found" + featureRef);
//create stories
try
{
for (int i = 1; i <= 25; i++)
{
DynamicJsonObject story = new DynamicJsonObject();
story["Name"] = "story " + i;
story["PlanEstimate"] = new Random().Next(2,10);
story["PortfolioItem"] = featureRef;
story["Project"] = projectRef;
CreateResult createResult = restApi.Create(workspaceRef, "HierarchicalRequirement", story);
story = restApi.GetByReference(createResult.Reference, "FormattedID");
Console.WriteLine("creating..." + story["FormattedID"]);
}
//read stories
DynamicJsonObject feature = restApi.GetByReference(featureRef, "UserStories");
Request storiesRequest = new Request(feature["UserStories"]);
storiesRequest.Fetch = new List<string>()
{
"FormattedID",
"PlanEstimate"
};
storiesRequest.Limit = 1000;
QueryResult storiesResult = restApi.Query(storiesRequest);
int storyCount = 0;
foreach (var userStory in storiesResult.Results)
{
Console.WriteLine(userStory["FormattedID"] + " " + userStory["PlanEstimate"]);
storyCount++;
}
Console.WriteLine(storyCount);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}

Import data into Quickbooks General Journal Entries

I try to import data from my POS System to Quickbooks to create General Journal entries. When i add some static(hard coded) data all saved successfully. But when I try to add data from my app QB add data to dataService but when i sync QB data didn't come. Please could you help with my problem. Here is my code.
//main code to add General Journal Entry to QB
var header = GenerateReportHeader(model);
var creditInfo = GenerateJournalEntryLines(model.CreditInformation, PostingTypeEnum.Credit);
var debitInfo = GenerateJournalEntryLines(model.DebitInformation, PostingTypeEnum.Debit);
var allLines = creditInfo.Concat(debitInfo).ToArray();
var result = new JournalEntry();
result.Header = header;
result.Line = allLines;
dataService.Add(result);
//Add Header
private JournalEntryHeader GenerateReportHeader(GeneralJournalModel model)
{
var result = new JournalEntryHeader
{
TxnDate = new DateTime(2013,7,1),
Status = "Payable",
Adjustment = false,
TxnDateSpecified = true
};
if (!String.IsNullOrEmpty(model.EntryNo))
{
result.DocNumber = model.EntryNo;
}
return result;
}
//Add Line
private JournalEntryLine[] GenerateJournalEntryLines(List<GeneralJournalEntryModel> model, PostingTypeEnum postType)
{
var result = new JournalEntryLine[model.Count];
for (int i = 0; i < model.Count; i++)
{
var journalEntryLine = model[i];
var account = GetAccountByNumber(journalEntryLine.AccountNumber);
var toAdd = new JournalEntryLine
{
AccountId = account.Id,
AccountType = account.Type,
AccountName = account.Name,
Amount = Convert.ToDecimal(journalEntryLine.Amount),
AmountSpecified = true,
PostingType = postType,
AccountTypeSpecified = true,
Id = new IdType(),
PostingTypeSpecified = true
};
if (journalEntryLine.EntityId != null)
{
toAdd.EntityId = GetEntityId(journalEntryLine.EntityType, journalEntryLine.EntityId);
toAdd.EntityType = GetEntityType(journalEntryLine.EntityType);
toAdd.EntityName = GetEntityName(journalEntryLine.EntityType, journalEntryLine.EntityId);
toAdd.EntityTypeSpecified = true;
}
result[i] = toAdd;
}
return result;
}
Did you check the SyncStatus, and find out why not?
This should be where you start:
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0500_quickbooks_windows/0600_object_reference/syncstatus
It will give you more detail about specifically why the data failed to sync over.

Not getting test case results(passed/failed/blocked) from TestSuite using TFS API

I am trying to get test case results(passed/failed/blocked) from TestSuite under a test plan.
Using below code to do this.
public List<ScoreBoard> GetTestStatistics(string teamProject, string selectedTestPlan)
{
// 1. Connect to TFS and Get Test Managemenet Service and Get all Test Plans
string serverName = "*********";
var server = new Uri(serverName);
var tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection(server);
var service = tfs.GetService<ITestManagementService>();
var testProject = service.GetTeamProject(teamProject);
var plan = testProject.TestPlans.Query("SELECT * FROM TestPlan").Where(tp => tp.Name == selectedTestPlan).FirstOrDefault();
List<ScoreBoard> scoreboards = new List<ScoreBoard>();
var testSuits = new List<IStaticTestSuite>();
if (plan.RootSuite != null)
{
testSuits.AddRange(TestSuiteHelper.GetTestSuiteRecursive(plan.RootSuite));
}
TestPlan testPlan = new TestPlan() { Id = plan.Id, Name = plan.Name, TestSuites = testSuits };
for (int i = 0; i < testPlan.TestSuites.Count; i++)
{
var ts = testPlan.TestSuites[i];
var scoreboard = new ScoreBoard();
scoreboard.TeamProject = teamProject;
scoreboard.TestPlan = selectedTestPlan;
scoreboard.Id = ts.Id;
scoreboard.Title = ts.Title;
scoreboard.State = ts.State.ToString();
scoreboard.TestCaseCount = ts.TestCases.Count;
int totalTestSteps = 0;
List<string> testStepScores = new List<string>();
foreach (var tc in ts.TestCases)
{
foreach (var a in tc.TestCase.Actions)
{
totalTestSteps = totalTestSteps + 1;
}
var testResults = testProject.TestResults.ByTestId(tc.TestCase.TestSuiteEntry.Id);
foreach (var result in testResults)
{
for (int actionIndex = 0; actionIndex < tc.TestCase.Actions.Count; actionIndex++)
{
var action = tc.TestCase.Actions[actionIndex];
if (!(action is ITestStep))
{
continue;
}
var step = action as ITestStep;
var topIteration = result.Iterations.FirstOrDefault();
if (topIteration == null)
continue;
var test = topIteration.Actions[actionIndex];
testStepScores.Add(topIteration.Actions[actionIndex].Outcome.ToString());
}
}
}
scoreboard.TestStepCount = totalTestSteps;
scoreboard.TestStepPassedCount = testStepScores.Where(tsp => tsp == "Passed").ToList().Count;
scoreboard.TestStepFailedCount = testStepScores.Where(tsp => tsp == "Failed").ToList().Count;
scoreboard.TestStepOutstandingCount = testStepScores.Where(tsp => tsp == "None").ToList().Count;
scoreboards.Add(scoreboard);
}
return scoreboards;
}
I am not getting correct result for passed test/Failed/Outstanding test count.
When I debugged into this, observed some property are showing message "Function evaluation disabled because a previous function evaluation timed out. You must continue execution to reenable function evaluation."
Can I get how many test cases are passed under the test suite ?
What could be the problem here?

eBay API AddItem call returns "Domestic shipping is required if AutoPay is specified" error

I'm new to eBay's API, and I'm trying to make an AddItem call. However, I keep getting an error:
Domestic shipping is required if AutoPay is specified
I copied the code in line-for-line from the SDK example code and it compiles and runs just fine, so I feel like there might have been some sort of change on eBay's end.
Here's some of my code:
static ItemType BuildItem()
{
ItemType item = new ItemType();
item.AutoPaySpecified = false;
item.Title = "Test Item";
item.Description = "eBay SDK sample test item";
item.ListingType = ListingTypeCodeType.Chinese;
item.Currency = CurrencyCodeType.USD;
item.StartPrice = new AmountType();
item.StartPrice.Value = 20;
item.StartPrice.currencyID = CurrencyCodeType.USD;
item.ListingDuration = "Days_3";
item.Location = "San Jose";
item.Country = CountryCodeType.US;
CategoryType category = new CategoryType();
category.CategoryID = "11104";
item.PrimaryCategory = category;
item.Quantity = 1;
item.ConditionID = 1000;
item.ItemSpecifics = buildItemSpecifics();
item.PaymentMethods = new BuyerPaymentMethodCodeTypeCollection();
item.PaymentMethods.AddRange(
new BuyerPaymentMethodCodeType[] { BuyerPaymentMethodCodeType.PayPal }
);
item.PayPalEmailAddress = "me#ebay.com";
item.DispatchTimeMax = 1;
item.ShippingDetails = BuildShippingDetails();
item.ReturnPolicy = new ReturnPolicyType();
item.ReturnPolicy.ReturnsAcceptedOption = "ReturnsAccepted";
AmountType amount = new AmountType();
amount.Value = 2.8;
amount.currencyID = CurrencyCodeType.USD;
item.StartPrice = amount;
return item;
}
static NameValueListTypeCollection buildItemSpecifics()
{
NameValueListTypeCollection nvCollection = new NameValueListTypeCollection();
NameValueListType nv1 = new NameValueListType();
nv1.Name = "Platform";
StringCollection nv1Col = new StringCollection();
String[] strArr1 = new string[] { "Microsoft Xbox 360" };
nv1Col.AddRange(strArr1);
nv1.Value = nv1Col;
NameValueListType nv2 = new NameValueListType();
nv2.Name = "Genre";
StringCollection nv2Col = new StringCollection();
String[] strArr2 = new string[] { "Simulation" };
nv2Col.AddRange(strArr2);
nv2.Value = nv2Col;
nvCollection.Add(nv1);
nvCollection.Add(nv2);
return nvCollection;
}
static ShippingDetailsType BuildShippingDetails()
{
ShippingDetailsType sd = new ShippingDetailsType();
sd.ApplyShippingDiscount = true;
AmountType amount = new AmountType();
amount.Value = 2.8;
amount.currencyID = CurrencyCodeType.USD;
sd.PaymentInstructions = "eBay .Net SDK test instructions";
// shipping type and shipping service options
sd.ShippingType = ShippingTypeCodeType.Flat;
ShippingServiceOptionsType shippingOptions = new ShippingServiceOptionsType();
shippingOptions.ShippingService = ShippingServiceCodeType.ShippingMethodStandard.ToString();
amount = new AmountType();
amount.Value = 1;
amount.currencyID = CurrencyCodeType.USD;
shippingOptions.ShippingServiceAdditionalCost = amount;
shippingOptions.ShippingServicePriority = 1;
amount = new AmountType();
amount.Value = 1.0;
amount.currencyID = CurrencyCodeType.USD;
shippingOptions.ShippingInsuranceCost = amount;
sd.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection(
new ShippingServiceOptionsType[] { shippingOptions }
);
return sd;
}
I've tried to set item.AutoPay = false; and item.AutoPaySpecified = false; - neither of those seem to do anything. I've searched the docs for any reference to something about domestic shipping, but I'm not finding anything.
Does anyone have any idea why this might be happening?
Your shippingOptions field is missing a ShippingServiceCost, try changing the line:
shippingOptions.ShippingServiceAdditionalCost = amount;
to
shippingOptions.ShippingServiceCost = amount;
or add an assignment to ShippingServiceCost.
"Domestic shipping is required if AutoPay is specified" seems to mean that some conditional (i.e. depending on the type of shipping) field is missing from the shipping options. I ran into the same error when trying to add all the necessary fields for calculated shipping - without all the fields, eBay interprets it as flat-rate shipping that is missing the ShippingServiceCost field.

Categories