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

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);
}

Related

Mocking a method to produce different values on every call [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 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.

Should I assign object properties when initializing or after initializing? [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 4 years ago.
Improve this question
I have an object obj1 with 11 properties.
Is it better to do this
Obj obj1 = new Obj()
{
prop1 = int.Parse(data.Rows[0]["RequestId"].ToString())
prop2 = IsBoss = (bool)data.Rows[0]["IsBoss"]
///etc...
}
or should I do
{
Obj obj1 = new Obj(){}
obj1.prop1 = int.Parse(data.Rows[0]["RequestId"].ToString())
obj1.prop2 = IsBoss = (bool)data.Rows[0]["IsBoss"]
///etc...
}
Also as a side question, when my data rows are null, an exception "Input string was not in a correct format" gets thrown because the field from the database is null. Typically the data wouldnt be null but would it be best to use a ternary operator to check if null or should i do a case in the sql qry.
Like the other answers, how you instantiate an object is up to you. Personally, I used to instantiate them and assign the properties all in one statement. The issue that I kept running into is when a had a property that failed to make it back from the database (like your null exception scenario), the the exception wouldn't give me an accurate line number. For that reason, I've moved to instantiating the object, then assigning the properties. This way, you'll know exactly which line/property is causing the issue.
MyClass obj = new MyClass();
obj.PropertyOne = "";
obj.PropertyTwo = "";
//etc...
As far as your second question goes, I handle nulls by using a ternary in combination with the IsDBNull() method on the DataTableReader.
MyClass obj = new MyClass();
obj.PropertyOne = rdr.IsDBNull(rdr.GetOrdinal("RequestId")) ? 0
: rdr.GetInt32(rdr.GetOrdinal("RequestId"));
I prefer setting object properties on initialization as per the first example, I think the code looks cleaner and better contained, but that is more of a personal preference.
For your second question when data is null coming back from the database you've got a few options.
{
var obj1 = new Obj()
{
prop1 = int.TryParse(data.Rows[0]["RequestId"]?.ToString(), out int val) ? val : -1,
prop2 = IsBoss = bool.TryParse(data.Rows[0]["IsBoss"].ToString(), out bool isBoss) ? isBoss : false
}
}
Haven't tested but something like that should work, but it's not clean. I'd separate out the parsing into its own method or block. To help the code breathe a little.
Something like this:
{
if(!(int.TryParse(data.Rows[0]["RequestId"]?.ToString(), out int requestId)))
{
requestId = -1;
}
bool.TryParse(data.Rows[0]["IsBoss"]?.ToString(), out IsBoss);
var obj1 = new Obj()
{
prop1 = requestId,
prop2 = IsBoss
}
}

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?

copying one objects data to other? [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 8 years ago.
Improve this question
I need to update EF record, in method I have EF object and another new objct which I want to use to update data from. But I m not sure how to copy data from new object to existing one.
Help please.
Here is my code:
public int PostHomeLead(string _lead)
{
try
{
int result = 0;
Lead lead = new Lead();
lead = new JavaScriptSerializer().Deserialize<Lead>(_lead);
//check if lead exist with same session id, if so update it other wise add new.
Lead existingLead = new Lead();
existingLead = db2.HomeLoanCustRepo.GetByID(lead.Lead_id);
if (existingLead == null)
{
db2.HomeLoanCustRepo.Insert(lead);
db2.Save();
result = 1;
}
else
{
db2.HomeLoanCustRepo.Update(lead);
db2.Save();
result = 1;
}
return result;
}
catch(Exception ex)
{
throw ex;
}
}
Either map the properties manually:
existingLead.Foo = deserializedLead.Foo;
existingLead.Bar = deserializedLead.Bar;
existingLead.Baz = deserializedLead.Baz;
Or use a library that does this, like AutoMapper.
As for your comment, creating a deep copy is what you seem to be after. Note this allows for overposting or mass assignment when you don't verify which properties may be updated. You'll need to Attach() the cloned object when using cloning or mapping, as it will not be the same object as returned by GetByID(), so Entity Framework's change tracker won't recognize it.

Why are the properties of anonymous types in C# read-only? [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 10 months ago.
Improve this question
In C#, the properties of anonymous types are read-only:
var person = new { Surname = "Smith", OtherNames = "John" };
person.Surname = "Johnson"; // ERROR: .Surname is read-only
Of course I can declare a real class if I want writable fields or properties, but regardless, what is the reasoning behind this design decision to make the properties read-only?
Interesting article on that here. From there ...
... [B]y ensuring that the members do
not change, we ensure that the hash is
constant for the lifetime of the
object.This allows anonymous types to
be used with collections like
hashtables, without actually losing
them when the members are modified.
There are a lot of benefits of
immutabilty in that, it drastically
simplifies the code that uses the
object since they can only be assigned
values when created and then just used
(think threading)
Unfortunately features like "top level statements" seem to be more important than the ability to pass complex data around and manipulate it as needed without having to create a class for that data. Its a HUGE gap in C# who's omission makes little sense to me. You basically have to use Dictionary<string,object> as this is the only way to do this. But let me ask any C# designers who might encounter this page, which is cleaner and less verbose between these 2 code snippets?
var data = new
{
Username = "My Username",
FullName = "John Smith",
Age = 22,
Salary = 11.5,
IsEmployee = true,
DOB = DateTimeOffset.UtcNow,
};
data.FullName = "Hello worlder";
var data2 = new Dictionary<string, object>
{
["Username"] = "My Username",
["FullName"] = "John Smith",
["Age"] = 22,
["Salary"] = 11.5,
["IsEmployee"] = true,
["DOB"] = DateTimeOffset.UtcNow,
};
data["FullName"] = "john smith";

Categories

Resources