Mocking a method to produce different values on every call [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
As part of a test, I wish to mock a Get() method using Moq such that it returns a popped value from a Stack every time it’s called.
Unfortunately, Moq’s Setup() methods are only run once and thus, each Get() within my test returns the same top value from the stack on every call.
My test kicks off a process in which multiple Get() methods are called. How would I mock this Get() method such that it pops a new value every time of off a orderedGetOutputs stack?

How about this:
public interface ISomeInterface
{
public string SomeValue { get; set; }
}
[Fact]
public void PropertyReturnsDifferentValueOnEachCall()
{
var stack = new Stack<string>();
stack.Push("World");
stack.Push("Hello");
var mock = new Mock<ISomeInterface>();
mock.SetupGet(s => s.SomeValue).Returns(() => stack.Pop());
// Because the method signature of stack.Pop() matches
// the expectation of Returns(), you could also write
// mock.SetupGet(s => s.SomeValue).Returns(stack.Pop);
var instance = mock.Object;
var resultOne = instance.SomeValue;
var resultTwo = instance.SomeValue;
Assert.NotEqual(resultOne, resultTwo);
}
When mocking a normal method you use .Setup(), but when you mock a property getter you have to use .SetupGet(). Regardless of what you mock, the .Returns() overload takes also a matching Func<> that can do whatever needed.

Moq has a specific function called “SetupSequence”. This will allow you to chain setup and return calls. Either that or you can pre populate the stack with information you’ll need for each call.

Related

Best practice to unit test a ViewModel in ASP .NET [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am creating unit tests for my code, I have a question about one of them:
[TestMethod]
public void Delete_Id()
{
// Arrange
Mock.Arrange(() => journalRepository.GetJournalById(1)).Returns(new Journal
{
Id = 1,
Description = "TestDesc",
FileName = "TestFilename.pdf",
Title = "Tester",
UserId = 1,
ModifiedDate = DateTime.Now
});
// Act
PublisherController controller = new PublisherController(journalRepository, membershipRepository);
ViewResult result = controller.Delete(1) as ViewResult;
// Assert
JournalViewModel model = result.Model as JournalViewModel;
Assert.AreEqual(model.Description, "TestDesc");
}
As you can see int he code above, I created a Journal object with several properties and sent it to my PublisherController for testing. However in the Assert part of the code, I am only testing one of the properties.
My question is: is it enough to test one of the properties, or should I test them all? And if I should test them all, is it possible to automate it, instead of test each propertiy of the returned object?
What is the best practice in this case?
In my opinion, testing all available properties will result into a more reliable test result. By doing so, you will be able to determine bugs where the controller changed a property value even though it wasn't meant to do so.
You'd just have to use Assert for each property to test (I'm not aware of anyway to automate this ATM).
Take note that unit testing is meant to be thorough. If you are not constrained by time then better make sure everything runs smoothly by testing everything as much as possible.
Best practice in this case would be primarily opinion based.
However, if you want to compare the entire object you could have the object as a variable and then compare them.
[TestMethod]
public void Delete_Id() {
// Arrange
var expected = new Journal {
Id = 1,
Description = "TestDesc",
FileName = "TestFilename.pdf",
Title = "Tester",
UserId = 1,
ModifiedDate = DateTime.Now
};
Mock.Arrange(() => journalRepository.GetJournalById(1)).Returns(expected);
var controller = new PublisherController(journalRepository, membershipRepository);
// Act
var result = controller.Delete(1) as ViewResult;
var model = result.Model as JournalViewModel;
// Assert
Assert.AreEqual(expected, model);
}

SessionBag missing in servicestack version 4.5.0 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to servicestack and using servicestack version 4.5.0.
With reference to the ServiceStack 'session' missing?
Where can I find this base.SessionBag property ? with base keyword I am getting
these intellisense
please help me.
what does this line means:
Inside a Service the dynamic untyped Session Bag was renamed to base.SessionBag.
what does this line means:
Inside a Service the dynamic untyped Session Bag was renamed to base.SessionBag.
when I write base. I find following intellisense
base.Session //-- Property Method
base.SaveSession //--- Extension
base.SessionAs<>
base.SessionFactory //-- Property Method
public class EntryService : Service
{
public object Post(Entry request)
{
var date = request.Time.Date;
var trackedData = (TrackedData)Session= date.ToString();
if(trackedData == null)
trackedData = new TrackedData { Goal = 300 };
trackedData.Total += request.Amount;
Session[date.ToString()] = trackedData;
return new EntryResponse { Id = 1};
}
}
i want like this
Session[date.ToString()] = trackedData;
but an error occurs Cannot apply indexing with [] to an expression of type ServiceStack.CacheAccess.ISession
You have to inherit from ServiceStack's Service base class. You can then access the dynamic Session Bag with base.SessionBag.

ASP.NET if route parameter is not given then do something [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've got some routing with parameters set-up in ASP.NET MVC 4 + Razor.
I am passing a parameter of {id} to the controller... and then on the controller I want to check the following:
A. if the id exists in the database, return view
B. if the id was not provided, redirect to Index
I've no idea how to go about doing those - and searching around doesn't really provide any information.
Could someone show me how to do an if / else statement to check if {id} has been provided?
The controller:
public ActionResult View(int id)
{
return View();
}
You can make your method parameter a nullable int so that it will work for the request urls such as
yourDomainName/yourController/view and yourDomainName/yourController/view/25
public ActionResult View(int? id)
{
if(id!=null) // id came in the request
{
int postId= id.Value;
var postViewModel = new PostViewModel { Id=postId};
// Use postId to get your entity/View model from db and then return view
// The below is the code to get data from Db.
// Read further if your data access method is different.
var db = new MyDbContext()
var post=db.Posts.FirstOrDefault(x=>x.Id==postId);
if(post!=null)
{
postViewModel.Title = post.Title;
return View(postViewModel);
}
return View("PostNotFound"); // Make sure you have this view.
}
//If code reaches here, that means no id value came in request.
return RedirectToAction("Index");
}
Assuming MyDbContext is your DbContext class and you are using Entity framework for data access. If your data access method is different ( ADO.NET/NHibernate etc..), You may update that part of code with your data access code.

What are C# chaining functional approach caveats? What to do with "ifs"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Recently I watched Pluralsight course "Functional programming in C#". And rewrote some methods in my hobby project. Now they look like this:
public override CommandLineResult GetResult()
{
return Disposable.Using(new IndicatorRepository(), repo =>
{
return repo.AddOrUpdateIndicator(Indicator, Value, DateTimeExtensions.LocalNow().Date);
})
.Map((p) => new NumericIndicatorRecorderedModel()
{
Id = Guid.NewGuid().ToString(),
DbActionPreformed = true,
IsRewritten = Convert.ToBoolean(p),
IndicatorName = Indicator,
Value = Value,
ValueDate = ValueDate
})
.Map((model) => new CommandLineResult()
{
ActionName = "~/Views/CommandLine/_clresult_NumericIndicatorRecorderedModel.cshtml",
Model = model
});
}
There's something pretty about this chaining approach (I removed Using with Disposable class, at every step I have expressions, not statements, etc.).
But the questions are:
Does not this approach covers some dangers? and what are they? (isn't it more difficult to debug for example)
What usually people do in terms of chaining approach, if it is required to branch the flow of code execution? Break chain with ifs somewhere? Write "map-if" functional extensions (would not that approach create spaghetti code?)?
UPDATE: more specific question regarding this issue
What approach to implement code branching is better - to break chaining like this:
public string GetResult(bool param) {
if (param) {
return MyClass.DoOneWay(p =>...).AlsoDo(q =>...).ToString();
}
else
{
return MyClass.DoOtherWay(p =>...).AlsoDo(q =>...).ToString();
}
}
Or to implement functional if-helpers, like this:
public string GetResult(bool param)
{
return MyClass.DoIf(param, p => ...., q => ....).AlsoDo(q =>...).ToString();
}
And what to do, if there're much more options then just true/false?
How to "functionaly" implement "switch" branching?

how to return the list of integer values to a method in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have a method in my repository which needs to provide list of integer values but I am getting the first column values only .. how can i get the all column values in my service..
this is my method in repository:
public List<int> GetChartInfo(string lineNo, string shiftDateTime, string station)
{
string query = string.Format("SELECT SUM(QTY_BUILD) AS BUILD_QTY, SUM(QTY_FAIL) AS FAIL_QTY, "+
"DATEPART(HH,BUILD_HOUR) AS SHIFT_HOURS FROM {0} WITH (NOLOCK) "+
"WHERE LINE_NO='{1}' AND BUILD_HOUR >='{2}' AND STATION='{3}' "+
"GROUP BY DATEPART(HH,BUILD_HOUR) ORDER BY SHIFT_HOURS ",_tableName, lineNo, shiftDateTime, station);
return MitecsRepository.Fetch<int>(query);
}
and i called this method in my service as follows:
var QtyBuildList = _qtyBuildRepository.GetChartInfo(cellName, _currentShiftDateTime, tableName);
QtyBuildList is getting only build_qty data only .. how can i get the fail_qty and shift_hours data also.
Why don't you create a class and return a list of this class. For example
public class BuildData
{
public int BuildQty {get;set;}
public int FailQty {get;set;}
public int ShiftHours {get;set;}
}
And then create a list
List<BuildData> BuildDataList = new List<BuildData>();
You can then loop around your data like;
while (ResultSet.Read())
{
BuildData data = new BuildData();
data.BuildQty = Convert.ToInt64(ResultSet["BUILD_QTY"];
data.FailQty = Convert.ToInt64(ResultSet["FAIL_QTY"];
data.ShiftHours = Convert.ToInt64(ResultSet["SHIFT_HOURS "];
BuildDataList.Add(data);
}
return BuildDataList;
So you are returning a list of BuildData rather than a List for just one of your columns.
according to the definition of your method you are supossed to get back only a list of integers.
public List<int> GetChartInfo(
You can create a custom Class that matches the values you need and that return a list of these objects where every object represents one row result from the query.
Another thing, you could do is to to turn the query into a list.
var x = MitecsRepository.Fetch<int>(query).ToList();
then either
return x;
and change the definition of the method to the following
public object GetChartInfo(
so you have it boxed.
Or you can do something like this if you want only one column
return x.Select(p=>p.Item1)
There is ya lot of stuff you can do But I would still tell you to consider using EF. Makes stuff like this much easier to solve.

Categories

Resources