Unit Testing ICommand and Methods - c#

I have developed an WPF application using MVVM as a architecture and am writing some unit tests as part of this. In my view I have a button that is bound to a property in the ViewModel which can be seen below.
ViewModel
public ICommand MoreInfoCommand
{
get
{
if (_moreInfoCommand == null)
{
_moreInfoCommand = new RelayCommand(parameter => OpenLink());
}
return _moreInfoCommand;
}
}
private void OpenLink()
{
try
{
Process.Start("https://www.google.com/");
}
catch
{
// catch error...
}
}
In my unit testing I have created the following unit test:
UnitTest
[Description("Test MoreInfoCommand")]
[TestMethod]
public void TestMoreInfoCommand()
{
viewModel vm = new viewModel();
Assert.IsTrue(vm.MoreInfoCommand.CanExecute(null));
}
Currently this tests the the property to see if when the button is clicked in the UI the relevant method can be executed. This passes as the conditions are met, however its my understanding I need to test the functionality as well. With this in mind how do I, for example tests that the correct functionality occurs when the button is clicked. I.e how to test what occurs when the ICommand MoreInfoCommand is executed as a result of button click in the UI.
I know private methods can be tested directly, but should in my unit testing I be checking the functionality as well and if so, how can I do this.
Thanks in advance.

Your view model isn't really testable. If you want to it to be, you should replace the call to the static Process.Start method with a call to a method of a interface that you inject the view model with:
public ViewModel(IProcessLoader processLoader) =>
_processLoader = processLoader;
//...
private void OpenLink()
{
try
{
_processLoader.Start("https://www.google.com/");
}
catch
{
// catch error...
}
}
You could then mock the interface in your unit test, for example using a mocking framwork like Moq:
[TestMethod]
public void TestMoreInfoCommand()
{
//Arrange
Mock<IProcessLoader> processLoader = new Mock<IProcessLoader>();
viewModel vm = new viewModel(processLoader.Object);
ICommand command = vm.MoreInfoCommand;
//Act
command.Execute(null);
//Assert
processLoader.Verify(x => x.Start(It.IsAny<string>()));
}
In the real app, you would implement the interface as a wrapper around Process.Start:
public interface IProcessLoader
{
void Start(string s);
}
public class ProcessLoader : IProcessLoader
{
public void Start(string s) => Process.Start(s);
}
It's important to realize that you should only verify that the method is called from the view model. A unit test against the view model class should not test the functionality of the Process class. The resposibility of the view model ends when Start has been called.
.NET and the underlying OS is responsible for what the Process class actually does. You should not test this but only your own code.

vm.MoreInfoCommand.CanExecute(null) would only call the canExecute method in your RelayCommand, but you did not provide any. CanExecute tells nothing about whether OpenLink would perform successfully or not.
Although I am no unit test specialist, if your code real looks like this, I doubt if it's worth to write a unit test for it in the first place, because it is so very simple.
As the comment from user auburg states, you can check, whether the process starts, although the process's name would depend on which browser was the standard browser. Also, you would have to wait for some time for the process to start. And maybe there was a process with the same name already running, lots of chances for trouble.
If you really want, you can check, if one of the well known mocking frameworks, e.g. Moq or Rhino Mocks, is able to mock away Process.Start.

Related

Unit test for void method with Interface as parameter

New to Unit testing, I have below sample code and I want to create a unit test for this , Please suggest what should i do to create a unit test for this ? any link or pointers would be helpful to start
public class UserNotification : Work
{
public override void Execute(IWorkContext iwc)
{
throw new InvalidWorkException($"some message:{iwc.Name} and :{iwc.Dept}");
}
}
Edit: using MSTest for Unit testing
First, you need a test project alongside with your regular project.
You can pick from these three:
MSTest
nUnit
xUnit
All of these should have a project template in VS2022.
xUnit is a popular one, so let's pick that. The usual naming convention for test projects is YourProject.Tests. Rename UnitTest1.cs class to UserNotificationTests.cs.
As simple as it gets, you can now start writing your tests. In xUnit, a method with [Fact] attribute is a test method.
using Xunit;
namespace MyProject.Tests
{
public class UserNotificationTests
{
[Fact]
public void Execute_Should_Throw_InvalidWorkException_With_Message()
{
}
}
}
Don't think these methods as the methods in the code, naming should be close to English sentences and should reveal the intent as a regular sentence.
Classic approach to unit testing has three phases:
Arrange: Take instances of your objects, set your expected output, mock dependencies, make them ready.
Act: Call the actual action you want to test.
Assert: Check if how your actual output relates to your expected output.
Let's start with arranging.
We need a new instance of UserNotification class so we can call Execute().
We need any dummy IWorkContext object so we can pass it. We'll use NSubstitute library for that.
// Don't forget to add using NSubstitute
// Arrange
var userNotification = new UserNotification();
var workContext = Substitute.For<IWorkContext>();
workContext.Name = "testName";
workContext.Dept = "testDept";
Now you act, and invoke your method:
// Act
Action act = () => userNotification.Execute(workContext);
And lastly we assert. I highly recommend FluentAssertations library for asserting.
// Assert
act.Should().Throw<InvalidWorkException>()
.WithMessage($"some message:{workContext.Name} and :{workContext.Dept}");
Navigate to View > Test Explorer and run your tests, you should see something similar to this:
Congratulations, you wrote your first unit test.
Here's the final version of your test code:
using FluentAssertions;
using NSubstitute;
using System;
using Xunit;
namespace MyProject.Tests
{
public class UserNotificationTests
{
[Fact]
public void Execute_Should_Throw_InvalidWorkException_With_Message()
{
// Arrange
var userNotification = new UserNotification();
var workContext = Substitute.For<IWorkContext>();
workContext.Name = "testName";
workContext.Dept = "testDept";
// Act
Action act = () => userNotification.Execute(workContext);
// Assert
act.Should().Throw<InvalidWorkException>()
.WithMessage($"some message:{workContext.Name} and :{workContext.Dept}");
}
}
public class UserNotification : Work
{
public override void Execute(IWorkContext iwc)
{
throw new InvalidWorkException($"some message:{iwc.Name} and :{iwc.Dept}");
}
}
public abstract class Work
{
public virtual void Execute(IWorkContext iwc) { }
}
public interface IWorkContext
{
public string Name { get; set; }
public string Dept { get; set; }
}
public class InvalidWorkException : System.Exception
{
public InvalidWorkException() { }
public InvalidWorkException(string message) : base(message) { }
public InvalidWorkException(string message, System.Exception inner) : base(message, inner) { }
protected InvalidWorkException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
Writing tests feels a lot different than writing regular code. But in time you'll get the hang of it. How to mock, how to act, how to assert, these may vary depending on what you are testing. The main point is to isolate the main thing you want to unit test, and mock the rest.
Good luck!
Because your title mentions specifically that you're trying to test a method with a void return type; I infer that you've already been testing methods with actual return values, and therefore that you already have a test project and know how to run a test once it is written. If not; the answer written by Mithgroth is a good explanation on how to get started on testing in general.
Your test is defined by the behavior that you wish to test. Your snippet has no behavior, which makes it hard to give you a concrete answer.
I've opted to rewrite your example:
public class UserNotification : Work
{
public override void Execute(IWorkContext iwc)
{
var splines = iwc.GetSplines();
iwc.Reticulate(splines);
}
}
Now we have some behavior that we want to test. The test goal is to answer the following question:
When calling Execute, does UserNotification fetch the needed splines and reticulate them?
When unit testing, you want to mock all other things. In this case, the IWorkContext is an external dependency, so it should be mocked. Mocking the work context allows us to easily configure the mock to help with the testing. When we run the test, we will pass an IWorkContext object which acts as a spy. In essence, this mocked object will:
... have been set up to return a very specific set of splines, one that we chose for the test's purpose.
... secretly record any calls made to the Reticulate method, and tracks the parameters that were passed into it.
Before we get into the nitty gritty on how to mock, we can already outline how our test is going to go:
[Test]
public void ReticulatesTheContextSplines()
{
// Arrange
IWorkContext mockedContext = ...; // This comes later
UserNotification userNotification = new UserNotification();
// Act
userNotification.Execute(mockedContext);
// Assert
// Confirm that Reticulate() was called
// Confirm that Reticulate() was given the result from `GetSplines()`
}
There's your basic unit test. All that's left is to create our mock.
You can write this yourself if you want. Simply create a new class that implements IWorkContext, and give it some more public properties/methods to help you keep track of things. A very simple example would be:
public class MockedWorkContext : IWorkContext
{
// Allows the test to set the returned result
public IEnumerable<Spline> Splines { get; set; }
// History of arguments used for calls made to Reticulate.
// Each call will add an entry to the list.
public List<IEnumerable<Spline>> ReticulateArguments { get; private set; } = new List<IEnumerable<Spline>>();
public IEnumerable<Spline> GetSplines()
{
// Returns the preset splines that the test configured
return this.Splines;
}
// Mocked implementation of Reticulate()
public void Reticulate(IEnumerable<Spline> splines)
{
// Does nothing except record what you passed into it
this.ReticulateArguments.Add(splines);
}
}
This is a very simplified implementation, but it gets the job done. The test will now look like this:
[Test]
public void ReticulatesTheContextSplines()
{
// Arrange
IEnumerable<Spline> splines = new List<Spline>() { new Spline(), new Spline() }; // Just create some items here, it's random test data.
IWorkContext mockedContext = new MockedWorkContext();
mockedContext.Splines = splines;
UserNotification userNotification = new UserNotification();
// Act
userNotification.Execute(mockedContext);
// Assert - Confirm that Reticulate() was called
mockedContext.ReticulateArguments.Should().HaveCount(1);
// Confirm that Reticulate() was given the result from `GetSplines()`
mockedContext.ReticulateArguments[0].Should().BeEquivalentTo(splines);
}
This test now exactly tests the behavior of your method. It uses the mocked context as a spy to report on what your unit under test (i.e. UserNotification) does with the context that you pass into it.
Note that I am using FluentAssertions here, as I find it the most easily readable syntax. Feel free to use your own assertion logic.
While you can write your own mocks; there are mocking libraries that help cut down on the boilerplating. Moq and NSubstitute are the two biggest favorites as far as I'm aware. I personally prefer NSubstitute's syntax; but both get the job done equally well.
If you want to use nunit the documentation with example is pretty easy to follow, link below.
Nunit documentation
And I think all other unit test framework have something similar to this.
[Test]
public void Execute_WhenCalled_ThrowArgumentException()
{
//Initialize an instance of IWorkContext
var iwc = new WorkContext();
//or use a Mock object, later on in assert use
//userNotification.Execute(iwc.Object)
var iwc = new Mock<IWorkContext>();
var userNotification = new UserNotification();
Assert.Throws(typeof(InvalidWorkException), () =>
{
userNotification.Execute(iwc)
});
}

Testing CRUD class.

I have some issue. Im writing some unit test in my project but i don't know how to test my CRUD methods.. Maybe they are not testable ;/
This is one of my methods:
public static void IncrementInvalidLoginColumn(string login)
{
User user;
using (DTContext context = new DTContext())
{
try
{
user = context.Users.Where(u => u.Login.CompareTo(login) == 0).FirstOrDefault();
if (user.InvalidLogins < 3)
{
user.InvalidLogins = user.InvalidLogins + 1;
}
context.SaveChanges();
}
catch
{
}
}
}
Maybe someone will have idea what should i do.
It depends on what you mean by "unit" test. If you don't want your test to hit the database then your method is not testable (or at least not without some refactoring).
If hitting the database is acceptable (which would actually be an integration test) then you can definitely test your method.
Here are some steps:
1. Arrange the initial data. You use an instance of the DTContext directly in the test to put the system in a predefined state (basically you write some user records in the database)
You run the method you want to test (which in fact uses its own instance of the DTContext)
You use DTContext again to read the user information directly from the database and assert that the InvalidLogins property has incremented.
You need to make sure you delete any data that you put in manually.
This is the gist of DI:
public class Example {
private IDatabaseGateway myDatabase;
public Example(IDatabaseGateway myDb) {
myDatabase = myDb;
}
public void DoStuff() {
...
myDatabase.GetData();
...
}
}
You give your business class an abstraction of the database via the constructor, that is you inject your dependencies in the class that needs them.
Once you have this in place, in production code you pass in the constructor a concrete instance of IDatabaseGateway that goes to the actual database.
In the case of a unit test you pass it a mock instance of the same interface. The mock is a special object that you can setup/configure to return what you want. Various libraries exist for mocking (an easy one is Moq).
However without modifying your code too much, it is better to stick with integration testing that hits the database. It will give you a simple and valid test.
Especially since there are some pitfalls in mocking the DbContext in EF (ex. some queries may not work when you will use them in production, testing updates in EF with mocks is a bit trickier).
Ok so i read all of your posts and they was very helpful.
I use MOQ framework and this is example how i do it.
This is how Liviu M. told me to do for example:
public class CRUDclass
{
private DTContext _context;
public CRUDclass(DTContext myObj)
{
_context = myObj;
}
}
We have CRUD Class which are doing operations directly on our database. We have constructor with one argument and private field. This our context :)
This is (for example) my method in CRUDclass:
public bool AddUser(User user)
{
try
{
_context.Users.Add(user);
_context.SaveChanges();
return true;
}
catch
{
return false;
}
}
Ovecourse he have our DTContext class witch DBSet becouse i using entity framework. And after that i am able to write some test method:
[TestMethod]
public void Should_Add_User()
{
var mockSet = new Mock<DbSet<User>>();
var mockContext = new Mock<DTContext>();
mockContext.Setup(m => m.Users).Returns(mockSet.Object);
var usrCRUD = new UserCRUD(mockContext.Object);
var usr = new User();
usr.Login = "Login_Name";
usr.Email = "loginName#test.com";
usr.Password = "***";
usr.InvalidLogins = 0;
usr.RememberID = 0;
usrCRUD.AddUser(usr);
mockSet.Verify(m => m.Add(It.Is<User>(arg => arg.Login == "Login_Name")));
mockContext.Verify(m => m.SaveChanges(), Times.Once());
}
At first a have to set my fake object (Mock>).
This test method checks if our user was added to Mock :)
I hope it can help somebody, if anything will be unclear please write a question :)
The idea of unit tests is to test your ifs, switches, etc., not the database operations.
In your case you need an interface that is an abstration of DTContext. In the simplest case it might look as the following.
public interface IObjectContext : IDisposable
{
IEnumerable<User> Users { get; }
}
In more complicated cases you may need to use IQueryable<T> or IObjectSet<T> instead of IEnumerable<T>.
Add a partial class declaration of DTContext and make it implement IObjectContext. Add a constructor to the class that contains the method IncrementInvalidLoginColumn with a parameter of type IObjectContext. Now you can inject any instance of IObjectContext instead of creating it in your class. This instance can be a DTContext or a mock for testing. Your class is ready to be tested without connection to a real database.
NB. In case of instances of IDisposable it's better to inject a Func<IObjectContext> instead of IObjectContext. Then you can create an instance for each operation and dispose it immediately after.
If there are CRUD operations in your code then I will recommend to use MOQ framework for unit testing. Below links are quite helpful:
Quick Start
Code Project
Ideally you would inject your DTContext rather than creating a new one every time that the method is called. That way you could mock that object in your unit test and verify that it is called as expected.
Your constructor would look something like:
private readonly IDTContext _context;
public CrudClass(IDTContext context)
{
_context = context
}
With your method now looking like
public static void IncrementInvalidLoginColumn(string login)
{
User user;
try
{
user = _context.Users.Where(u => u.Login.CompareTo(login) == 0).FirstOrDefault();
if (user.InvalidLogins < 3)
{
user.InvalidLogins = user.InvalidLogins + 1;
}
_context.SaveChanges();
}
catch
{
// Handle errors
}
}
And then in your test, if you were using a framework like Moq, you would basically script how that object would behave and test against that. For instance, setting up the mocked IDTContext to always return the same user for your Users collection and SaveChanges() method will write the number of invalid logins to a variable that you could then test against.

unit testing with mock and possibility of unit testing

I am new in unit testing.
public List<BookList> GetBookList(int bookid)
{
List<BookList> _BookList = new List<BookList>();
//Consider if some wcf call is there then how we can develop unit test
using (DataClassesDataContext context = new DataClassesDataContext(_strConnectionStringName))
{
foreach (tblBook_Sel_BasedOnbookIDResult _tblBook_selResult in context.tblBook_Sel_BasedOnBookID(bookid))
{
BookList _bookListObject = new BookList();
//Setting the proerty here
_BookList .Add(_bookListObject);
}
}
return _BookList;
}
I want to write unit test for this method.Please suggest which scenario of the above function i can test through unit testing and how .I can understand better if you can elaborate with some code example and how mocking can help us in above scenario.Thanks in advance.
You have a strong dependency to data access class, so probably you should inject it, if you have context as class member,initialized by injection from constructor, you easily can mock it from your unit test; the best approach is to have a contructor with IDataAccess parameter.
EDIT:
probably there is some problem to this snippet, but the idea is:
public interface IDataClassesDataContext
{
tblBook_Sel_BasedOnbookIDResult tblBook_Sel_BasedOnBookID(int bookid);
}
public partial class DataClassesDataContext:IDataClassesDataContext
{
}
public class Class1
{
IDataClassesDataContext _context;
public Class1(IDataClassesDataContext context)
{
_context = context;
}
public List<BookList> GetBookList(int bookid)
{
List<BookList> _BookList = new List<BookList>();
//Consider if some wcf call is there then how we can develop unit test
using (_context)
{
foreach (tblBook_Sel_BasedOnbookIDResult _tblBook_selResult in _context.tblBook_Sel_BasedOnBookID(bookid))
{
BookList _bookListObject = new BookList();
//Setting the proerty here
_BookList.Add(_bookListObject);
}
}
return _BookList;
}
}
This function is a stretched out two-liner, where one of the lines is data access. This function would be one I'd mock to unit test those that rely on it. You cannot unit test it, because it relies on outside data sources and therefore is not a single unit. If external sources are involved, you can use integration testing instead.
Some possible scenarios:
bookId parameter is negative, zero and positive. You can use int.MaxValue and int.MinValue.
_strConnectionStringName is null, empty, invalid and valid.
Tests for possible exceptions that can be thrown by tblBook_Sel_BasedOnBookID method.
Based on properties of the BookList class, you can have multiple test cases.
Please note that you should be calling a mock tblBook_Sel_BasedOnBookID method here. This method does not really care what goes on inside tblBook_Sel_BasedOnBookID. However, it looks a tad difficult are you are dealing with concrete type here.
For service, again a mock service call should made instead to making a real service call and based on conditions it can return a hard coded result or an exception.

Unit Testing using Moq and MVP-VM

I am trying to perform an Unit Testing(Integration Test using Moq) in my code using MVP-VM patterns. I have a view, a viewmodel, and a presenter.
The presenter holds the actual functionality of my UIs.
The way I was trying to test my presenter is, like following.
public interface IMockView : IRealView
{
event EventHandler ButtonClickedEvent;
}
public interface IMockViewModel : IRealViewModel
{ }
public class MockPresenter : RealPresenter
{
private IMockView _view;
private IMockViewModel _viewModel;
public MyProperty { get; set; }
public MockPresenter (IMockView view, IMockViewModel viewModel)
:base(view, viewModel)
{
_view = view;
_viewModel = viewModel;
view.ButtonClickedEvent += (s, e) =>
{
//Do Something
this.MyProperty = Property retrieved from db.
};
}
}
And here is my test code.(I am using NUnit Test framework with Moq)
[Test]
public void TriggerCreateClicked()
{
var view = new Mock<IMockView>();
var viewModel = new Mock<IMockViewModel>();
var presenter = new MockPresenter(view.Object, viewModel.Object);
viewModel.Setup(x => x.IsValid).Returns(true)
.Raises(t => t.ButtonClickedEvent += null, EventArgs.Empty);
viewModel.Object.IsValid = true;
Assert.NotNull(presenter.MyProperty);
}
Basically, on my test case,
If ViewModel.IsValid returns true, I am raising the ButtonClickedEvent.
Then, inside of Presenter, I want to retrieve some property from db and store it in MyProperty. Then, I would like to test if this MyProperty is Not Null. If the test went through fine with no exception, presenter that has MyProperty should hold some values.
My question is, is it appropriate for me to create MockPresenter(not interface) that inherits RealPresenter(class) in order to perform Mock Test? Since my code in the RealPresenter does not provide any getters or setters to retrieve this Property, I decided to inherit RealPresenter by MockPresenter class in order not to impact on my RealPresenter. I have not seen any sample codes online that makes my approach feasible.
The first question is whether you are testing only one thing in your test method. In your case, I think you are testing two things in one method: raising event when validation returns true and retrieving data when event is handled. I suggest you separate them into two test methods.
The second question is you use Mock without verifying, which means all mocks in your test method is stubs. I guess in your method at least you will verify one.
The third question is I did not get what your real logic since you put some additional logic in your mock interface and test method.
I think in unit testing of WPF with MVVM, you might not have to test raising event handler since that is .Net framework's job. What you need test is event handler works correctly. If it through command binding you can mock the command to test the calling if command's implementation contains dependencies such database connection.

Help/advice needed with unit testing repositories

I am using .NET 4, NUnit and Rhino mocks. I want to unit test my news repository, but I am not sure of how to go about it. My news repository is what I will eventually be using to communicate to the database. I want to use it to test against fake/dummy data. Not sure if it is possible?? This is what I currently have:
public interface INewsRepository
{
IEnumerable<News> FindAll();
}
public class NewsRepository : INewsRepository
{
private readonly INewsRepository newsRepository;
public NewsRepository(INewsRepository newsRepository)
{
this.newsRepository = newsRepository;
}
public IEnumerable<News> FindAll()
{
return null;
}
}
My unit test looks like this:
public class NewsRepositoryTest
{
private INewsRepository newsRepository;
[SetUp]
public void Init()
{
newsRepository = MockRepository.GenerateMock<NewsRepository>();
}
[Test]
public void FindAll_should_return_correct_news()
{
// Arrange
List<News> newsList = new List<News>();
newsList.Add(new News { Id = 1, Title = "Test Title 1" });
newsList.Add(new News { Id = 2, Title = "Test Title 2" });
newsRepository.Stub(r => r.FindAll()).Return(newsList);
// Act
var actual = newsRepository.FindAll();
// Assert
Assert.AreEqual(2, actual.Count());
}
}
In the above code I am not sure what I need to mock. The code above compiles but fails in the NUnit GUI about a contructor value. I can only assume it has to do with the INewsRepository paramter that I need to supply to NewsRepository. I don't know how to do this in the test. Can someone please rectify my unit test so that it will pass in the NUnit GUI? Can someone also provide some feedback on if I am implementing my repositories correctly?
Being a newbie to mocking, is there anything that I need to verify? When would I need to verify? What is its purpose? I have been working through a couple of source code projects and some use verify and some don't.
If the above test passes, what does this prove to me as developer? What does another developer have to do to my repository to make it fail in the NUnit GUI?
Sorry for all the questions, but they are newbie questions :)
I hope soomeone can help me out.
As Steven has said, you're Asserting against the Mock NewsRepository in the above code.
The idea of mocking is to isolate the Code Under Test and to create fakes to replace their dependencies.
You use the Mock NewsRepository to test something that uses INewsRepository, in your case, you mention NewsService; NewsService will use your mock of INewsRepository.
If you search your solution for anything that uses INewsRepository.FindAll(), you will create a Mock Repository to test that code in isolation.
If you want to test something that calls your Service layer, you will need to mock NewsService.
Also, as Steven as said, there is no need for the NewsRepository to have a copy of itself injected by IoC, so:
public class NewsRepository : INewsRepository
{
private readonly INewsRepository newsRepository;
public NewsRepository(INewsRepository newsRepository)
{
this.newsRepository = newsRepository;
}
public IEnumerable<News> FindAll()
{
return null;
}
}
should become:
public class NewsRepository : INewsRepository
{
public IEnumerable<News> FindAll()
{
return null;
}
}
Once you have functionality in your FindAll() method that needs testing, you can mock the objects that they use.
As a point of style from the great Art Of Unit Testing initialisation of mock objects is best left out of the Setup method and carried out in a helper method called at the start of the method. Since the call to Setup will be invisible and makes the initalisation of the mock unclear.
As another point of style, from that book, a suggested unit test naming convention is: "MethodUnderTest_Scenario_ExpectedBehavior".
So,
FindAll_should_return_correct_news
could become, for example:
FindAll_AfterAddingTwoNewsItems_ReturnsACollectionWithCountOf2
I hope this makes the approach clearer.
Your FindAll_should_return_correct_news test method is not testing the repository, it is testing itself. You can see this when you simplify it to what it really does:
[Test]
public void FindAll_should_return_correct_news()
{
// Arrange
List<News> newsList = new List<News>();
newsList.Add(new News { Id = 1, Title = "Test Title 1" });
newsList.Add(new News { Id = 2, Title = "Test Title 2" });
// Act
var actual = newsList;
// Assert
Assert.AreEqual(2, actual.Count());
}
As you can see, what you're basically doing is creating a list, filling it and testing if it actually contains the number of records that you put in it.
When your repository does nothing else than database interaction (so no application logic) there is nothing to test using a unit test. You can solve this problem by writing integration tests for the repositories. What you can basically do with such a integration test is insert some records in a test database (use a real database though, not an in-memory database) and then call the real repository class to see if it fetches the expected records from your test database. All should be executed within a transaction and rolled back at the end of the test (this ensures these tests keep trustworthy).
When you're using a O/RM tool that allows you to write LINQ queries, you could also try a different approach. You can fake your LINQ provider, as you can see in this article.
Might want to read over this post by ayende

Categories