I'm using Nunit and Moq to test my asp.net mvc solution. Is this a good way to test that the model passed to the view is a correct object/collection?
[Test]
public void Start_Page_Should_Display_Posts()
{
var posts = new List<Post> {new Post {Id = 1}, new Post {Id = 2}};
var mock = new Mock<IRepository>();
mock.Setup(x => x.FindAll<Post>()).Returns(posts.AsQueryable());
var controller = new PostsController(mock.Object);
var result = controller.Index(null) as ViewResult;
var viewModel = controller.ViewData.Model as IEnumerable<Post>;
Assert.IsNotNull(result);
Assert.IsTrue(viewModel.Count() == mock.Object.FindAll<Post>().Count());
}
I understand that this kind of tests the framework, but hopefully you'll get my point. Can I trust this test?
Currently i'm a bit tired so don't hesitate to ask for an elaboration.
Thanks
MVVM – Unit Testing The idea behind unit testing is to take discrete chunks of code (units) and write test methods that use the code in an expected way, and then test to see if they get the expected results. Being code themselves, unit tests are compiled just like the rest of the project.
In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.
The main difference is the ability of MsTest to execute in parallel at the method level. Also, the tight integration of MsTest with Visual Studio provides advantages in both speed and robustness when compared to NUnit. As a result, I recommend MsTest.
ASP.NET Core API. In computer programming, unit testing is a software testing method by which individual units of source code are tested to determine whether they are fit for use.
No it doesn't test (only?) the framework. It tests that executing the action results in a ViewModel consisting of a not-null, collection of the same count as the one supplied in the mock.
You could simplify the last condition into
Assert.IsTrue(viewModel.Count() == posts.Count);
or even
Assert.IsTrue(viewModel.Count() == 2);
I mean it's a unit test, it's normal to have some hardcoded values in there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With