I'm using NSubstitute in an integration test by wrapping a real implementation with a mock, like this:
var realRepository = container.Get<IRepository>();
var proxyRepository = Substitute.For<IRepository>();
proxyRepository
.When(repo => repo.InsertValueForEntity(Arg.Any<int>(), Arg.Any<ValueForEntity>())
.Do(callInfo => realRepository
.InsertValueForEntity((int)callInfo.Args()[0], (ValueForEntity)callInfo.Args()[1]));
proxyRepository
.GetValueForEntity(Arg.Any<int>())
.Returns(callInfo => realRepository
.GetValueForEntity((int)callInfo.Args()[0]));
// assume these parameters are defined elsewhere
var factory = new EntityFactory(mock1, realDependency, mock2, proxyRepository);
var entity = factory.CreateEntity(/* args */); // <-- this is where proxyRepository.GetValueForEntity() should be called
proxyRepository.Received().InsertValueForEntity(entity.Id, dummyValue);
proxyRepository.Received().GetValueForEntity(Arg.Is(entity.Id));
Assert.That(entity.Value, Is.EqualTo(dummyValue));
What's strange to me about this is that I have another test using the .When().Do() technique like this, and it works just fine. And indeed it appears that the configuration for InsertValueForEntity works here also. However, the configuration for GetValueForEntity is not working, and I don't understand why. I put a breakpoint in the lambda and it never hits.
Is there something tricky about substitutes that I'm missing here?
There does not seem any obvious problem with the example code, so I am guessing it is an issue with some of the code not shown. Is it possible to post a runnable version that illustrates the problem? I also suggest adding NSubstitute.Analyzers to your project as it can help detect issues that sometimes causing confusing test behaviour.
Here's a simplified version that demonstrates everything working correctly. If it is possible to modify this to reproduce the problem that would be really helpful!
First, some supporting types:
public interface IRepository {
ValueForEntity GetValueForEntity(int v);
void InsertValueForEntity(int v, ValueForEntity valueForEntity);
}
public class RealRepository : IRepository {
private readonly IDictionary<int, ValueForEntity> data = new Dictionary<int, ValueForEntity>();
public ValueForEntity GetValueForEntity(int v) => data[v];
public void InsertValueForEntity(int v, ValueForEntity valueForEntity) => data[v] = valueForEntity;
}
public class ValueForEntity {
public int Id { get; set; }
}
Then a rough approximation of the subject being tested:
public class EntityFactory {
private readonly IRepository repo;
public EntityFactory(IRepository repo) => this.repo = repo;
public ValueForEntity CreateEntity(int id) {
repo.InsertValueForEntity(id, new ValueForEntity { Id = id });
return repo.GetValueForEntity(id);
}
}
Finally, here's a passing version of the posted test (I had XUnit rather than NUnit handy so changed the assertion and test attribute accordingly):
[Fact]
public void Example() {
var realRepository = new RealRepository();
var proxyRepository = Substitute.For<IRepository>();
proxyRepository
.When(repo => repo.InsertValueForEntity(Arg.Any<int>(), Arg.Any<ValueForEntity>()))
.Do(callInfo => realRepository
.InsertValueForEntity((int)callInfo.Args()[0], (ValueForEntity)callInfo.Args()[1]));
proxyRepository
.GetValueForEntity(Arg.Any<int>())
.Returns(callInfo => realRepository
.GetValueForEntity((int)callInfo.Args()[0]));
var factory = new EntityFactory(proxyRepository);
var entity = factory.CreateEntity(42 /* args */);
proxyRepository.Received().InsertValueForEntity(entity.Id, Arg.Any<ValueForEntity>());
proxyRepository.Received().GetValueForEntity(Arg.Is(entity.Id));
Assert.Equal(42, entity.Id);
}
I know the types don't exactly match, but hopefully you can use this working example to find out the main difference that is causing problems in your fixture.
As an aside, is it worth using a substitute at all here if you could just use realRepository?
Related
I have a code like this (I have to test a repo, you'll see the code below)
public class SomeClass
{
public AsyncPolicyWrap PropName { get; }
public SomeClass(...)
{
PropName = Policy.WrapAsync(someRetry,someCircuitBreaker)
// here there are passed some methods that return someRetry - AsyncRetryPolicy
// and someCircuitBreaker - AsyncCircuitBreakerPolicy
}
}
then I have another repo class
public class SomeRepo : ISomeRepo
{
private readonly AsyncPolicy _somePolicy;
public SomeRepo(..., SomeClass someClass) : base(...)
{
_somePolicy = someClass.PropName;
}
public async Task<Result<SomeDTO>> GetDTO(Guid someId)
{
var someResponse = await _somePolicy.ExecuteAsync(() =>
HttpClient.GetAsync(serviceName, $"endpointUrl"));
...
}
}
2 pieces of code above can't be changed cause they are in prod and I as a junior dev just have to cover code with tests if possible
I have tried to write a test like this
[TestMethod]
public async Task DoStuff()
{
var repository = DefaultSome();
var result = await repository.GetDTO(new Guid());
result.ShouldNotBeNull(); // don't pay attention I'll change stuff which has to be asserted
}
private SomeRepo DefaultSome(Some some = null)
{
some = some ?? A.Fake<ISome>();
/// HERE I TRIED TO MOCK STUFF IN DIFFERENT WAYS AND I HAVE AN ERROR
var policyWrap = A.Dummy<AsyncPolicyWrap>();
//var test = Policy.WrapAsync(A.Fake<AsyncRetryPolicy>(), A.Fake<AsyncCircuitBreakerPolicy>());
//var test = Policy.WrapAsync(A.Fake<IAsyncPolicy>(), A.Fake<IAsyncPolicy>());
A.CallTo(() =>
policyWrap.ExecuteAsync(A<Func<Task<HttpResponseMessage>>>._))
.Returns(new HttpResponseMessage(HttpStatusCode.OK));
var policy = A.Fake<RetryPolicies>();
A.CallTo(() =>
policy.PropName)
.Returns(policyWrap);
return new SomeRepo(some, ..., policy);
}
here is an error i get
I get similar for commented // var test = ... variats
Concrete vs Abstract
Whenever you need to mock something then rely on abstraction rather than concrete implementation.
AsyncPolicyWrap is a concrete class not an abstract like AsyncPolicy
Also as the exception says this class does not have a public parameterless constructor.
It has an internal ctor with 2 parameters:
internal AsyncPolicyWrap(AsyncPolicy outer, IAsyncPolicy inner)
: base(outer.ExceptionPredicates)
{
_outer = outer;
_inner = inner;
}
So, you should prefer AsyncPolicy abstract class or IAsyncPolicy interface.
With or without result
Please be aware that in Polly each Policy has two versions:
One which does not return any result
One which does return some result
Based on the SomeRepo's code your Policy should return an HttpResponseMessage.
So, you should use IAsyncPolicy<HttpResponseMessage> or AsyncPolicy<HttpResponseMessage> to indicate that your policy will return an HttpResponseMessage.
Mocking
Whenever you mock an IAsyncPolicy<HttpResponseMessage> then you don't have to recreate the combined policy (like you did in the comments). All you have to do is to define how should the ExecuteAsync behave.
Happy path:
var mockedPolicy = new Mock<IAsyncPolicy<HttpResponseMessage>>();
mockedPolicy
.Setup(policy => policy.ExecuteAsync(It.IsAny<Func<Task<HttpResponseMessage>>>()))
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));
Unhappy path:
var mockedPolicy = new Mock<IAsyncPolicy<HttpResponseMessage>>();
mockedPolicy
.Setup(policy => policy.ExecuteAsync(It.IsAny<Func<Task<HttpResponseMessage>>>()))
.ThrowsAsync(new HttpRequestException("Something bad happened"));
I've used moq to mock the policy but the same concept can be applied for FakeItEasy.
My WEB API project is using a Generic Repository that implements an interface like this:
public interface IGenericEFRepository<TEntity> where TEntity : class
{
Task<IEnumerable<TEntity>> Get();
Task<TEntity> Get(int id);
}
public class GenericEFRepository<TEntity> : IGenericEFRepository<TEntity>
where TEntity : class
{
private SqlDbContext _db;
public GenericEFRepository(SqlDbContext db)
{
_db = db;
}
public async Task<IEnumerable<TEntity>> Get()
{
return await Task.FromResult(_db.Set<TEntity>());
}
public async Task<TEntity> Get(int id)
{
var entity = await Task.FromResult(_db.Set<TEntity>().Find(new object[] { id }));
if (entity != null && includeRelatedEntities)
{
//Some Code
}
return entity;
}
}
Well now I want to test this service. for this I have used the following code:
public class CustomerControllerTest
{
CustomerController _controller;
ICustomerProvider _provider;
ICustomerInquiryMockRepository _repo;
public CustomerControllerTest()
{
_repo = new CustomerInquiryMockRepository();
_provider = new CustomerProvider(_repo);
_controller = new CustomerController(_provider);
}
[Fact]
public async Task Get_WhenCalled_ReturnsOkResult()
{
// Act
var okResult = await _controller.Get();
// Assert
Assert.IsType<OkObjectResult>(okResult);
}
[Fact]
public async Task GetById_UnknownCustomerIdPassed_ReturnsNotFoundResult()
{
// Act
var notFoundResult = await _controller.Get(4);
// Assert
Assert.IsType<NotFoundResult>(notFoundResult);
}
}
Which my tests are working fine by creating a fake non-generic service manually with mock data (In-Memory) like below, instead of using my real generic interface and it's implementation that uses my database as data-source:
public interface ICustomerInquiryMockRepository
{
Task<IEnumerable<CustomerDTO>> GetCustomers();
Task<CustomerDTO> GetCustomer(int customerId);
}
And it's implementation:
public class CustomerInquiryMockRepository : ICustomerInquiryMockRepository
{
public async Task<IEnumerable<CustomerDTO>> GetCustomers()
{
return await Task.FromResult(MockData.Current.Customers);
}
public async Task<CustomerDTO> GetCustomer(int CustomerId)
{
var Customer = await Task.FromResult(MockData.Current.Customers.FirstOrDefault(p => p.CustomerID.Equals(CustomerId)));
if (includeTransactions && Customer != null)
{
Customer.Transactions = MockData.Current.Transactions.Where(b => b.CustomerId.Equals(CustomerId)).ToList();
}
return Customer;
}
}
And the MockData.Current.Customers is just a simple fake (In-Memory) List of Customers. Long story short, the above tests are working fine, however I am feeling I have repeated my self a lot and so I have decided to use Moq library instead of creating fake service manually. For this purpose I have used Moq like this:
public class CustomerControllerTest
{
CustomerController _controller;
ICustomerProvider _provider;
//ICustomerInquiryMockRepository _repo;
Mock<ICustomerInquiryMockRepository> mockUserRepo;
public CustomerControllerTest()
{
mockUserRepo = new Mock<ICustomerInquiryMockRepository>();
//_repo = new CustomerInquiryMockRepository();
_provider = new CustomerProvider(mockUserRepo.Object);
_controller = new CustomerController(_provider);
}
[Fact]
public async Task Get_WhenCalled_ReturnsOkResult()
{
mockUserRepo.Setup(m => m.GetCustomers())
.Returns(Task.FromResult(MockData.Current.Customers.AsEnumerable()));
// Act
var okResult = await _controller.Get();
// Assert
Assert.IsType<OkObjectResult>(okResult);
}
[Fact]
public async Task GetById_UnknownCustomerIdPassed_ReturnsNotFoundResult()
{
//Arrange
I don't know how can I use Moq here and in the other parts of my tests
// Act
var notFoundResult = await _controller.Get(4);
// Assert
Assert.IsType<NotFoundResult>(notFoundResult);
}
Now my question is the Mock is working fine when I use it for Mocking the GetCustomers method because I simply paste the code from GetCustomers method in the CustomerInquiryMockRepository in the Returns method of the Mock object. However I don't really have any idea how can I use Mock for my other methods inside this Repository. Should I replace anything that I have in the Return method?
You can mock out your repository like so:
var mockUserRepo = new Mock<ICustomerInquiryMockRepository>();
mockUserRepo.Setup(x => x.GetCustomers())
.Returns(Task.FromResult(MockData.Current.Customers.AsEnumerable());
mockUserRepo.Setup(x => x.GetCustomer(It.IsAny<int>()))
.Returns(res => Task.FromResult(MockData.Current.Customers.ElementAt(res));
If you want to mock out specific values for GetCustomer, you can do:
mockUserRepo.Setup(x => x.GetCustomer(It.Is<int>(y => y == 4)))
.Returns(res => Task.FromResult(/* error value here */));
I think the key here is to use It.Is or It.IsAny based on how you want to mock out the object. Generally, you also want to mock out interfaces that are used in production code, instead of having production code depend on something with Mock or Test in the name. I would recommend against taking a production code dependency on something named ICustomerInquiryMockRepository, if that is indeed what you're doing and not just part of the MCVE you've provided.
Tests usually use mocking to test the workflow of an application at a high level, so you would usually want to mock out your services level, call a controller, and verify that the services were called as expected. For example:
// Production class sample
class ProductionController
{
public ProductionController(IService1 service1, IService2 service2) { }
public void ControllerMethod()
{
var service1Result = service1.Method();
service2.Method(service1Result);
}
}
// Test sample
// arrange
var expectedResult = new Service1Result();
var service1 = Mock.Of<IService1>(x => x.Method() == expectedResult);
var service2 = Mock.Of<IService2>(x => x.Method(It.Is<Service1Result>(y => y == expectedResult)));
var controller = new ProductionController(service1, service2);
// act
controller.ControllerMethod();
// assert
Mock.Get(service1).Verify(x => x.Method(), Times.Once);
Mock.Get(service2).Verify(x => x.Method(expectedResult), Times.Once);
As you can see from the example, you aren't checking the business logic of either of the services, you're just validating that the methods were called with the expected data. The test is built around verification of methods being called, not any particular branching logic.
Also, unrelated to your question, Moq also has a cool syntax you can use for simple mock setups:
var repo = Mock.Of<ICustomerInquiryMockRepository>(x =>
x.GetCustomers() == Task.FromResult(MockData.Current.Customers.AsEnumerable()));
You can use Mock.Get(repo) if you need to do additional setup on the repository. It's definitely worth checking out, I find it much nicer to read.
I have a class, a service, and two interfaces:
public class MyBasicObject
{
public MyBasicObject() { }
public int Id { get; set; }
public string Name { get; set; }
}
public interface ICacheProvider
{
T Get<T>(string key, Func<T> fetcher) where T:class;
}
public interface IMyBasicObjectRepository
{
MyBasicObject GetByName(string name);
}
public class MyBasicObjectService
{
public MyBasicObjectService(ICacheProvider cacheProvider,
IMyBasicObjectRepository repository)
{
CacheProvider = cacheProvider;
MyBasicObjectRepository = repository;
}
public ICacheProvider CacheProvider { get; set; }
public IMyBasicObjectRepository MyBasicObjectRepository { get; set; }
public MyBasicObject GetByName(string name)
{
return CacheProvider.Get<MyBasicObject>(name, () =>
MyBasicObjectRepository.GetByName(name));
}
}
Using RhinoMocks, I'd like to be able to verify that when MyBasicObjectService.GetByName("AnUniqueName") gets executed, so does CacheProvider.Get("AnUniqueName", () => MyBasicObjectRepository.GetByName("AnUniqueName")). I have a fixture set up like so:
[TestFixture]
public class MyBasicObjectServiceFixture
{
[Test]
public void GetByNameShouldCallCacheProviderFunction()
{
// Arrange
MockRepository mock = new MockRepository();
IMyBasicObjectRepository repo = mock.DynamicMock<IMyBasicObjectRepository>();
ICacheProvider cacheProvider = mock.DynamicMock<ICacheProvider>();
MyBasicObjectService service = new MyBasicObjectService(cacheProvider, repo);
cacheProvider.Expect(p => p.Get<MyBasicObject>("AnUniqueName", () => repo.GetByName("AnUniqueName")));
mock.ReplayAll();
// Act
var result = service.GetByName("AnUniqueName");
// Assert
mock.VerifyAll();
}
}
I would expect this test to pass, but when run, the assertion fails, notifying me that the function laid out in cacheProvider.Expect is not being called. Am I missing something reg. mocking out and testing methods that take parameters of Func<>?
Edit:
So if I do:
cacheProvider.Expect(p => p.Get<MyBasicObject>("AnUniqueName", () => repo.GetByName("AnUniqueName"))).IgnoreArguments();
(that is to say, add the IgnoreArguments() method onto the end of the expect call)
...the test passes just fine. I'm assuming, then, it's a problem with the argument passed in. Is there something I'm doing wrong in the expect where the cache provider method is getting called but it chokes on the anonymous method getting passed in?
The problem is that the two anonymous methods (the one in the Expect and the one which is created in GetByName are two different objects and therefor are not equal. You can fix that by partially matching the arguments like this:
cacheProvider.Expect(p => p.Get<MyBasicObject>(Arg<string>.Is.Equal("AnUniqueName"), Arg <Func<MyBasicObject>>.Is.NotNull));
What I ended up doing for the test was:
[TestFixture]
public class MyBasicObjectServiceFixture
{
[Test]
public void GetByNameShouldCallCacheProviderFunction()
{
// Arrange
MockRepository mock = new MockRepository();
IMyBasicObjectRepository repo = mock.DynamicMock<IMyBasicObjectRepository>();
ICacheProvider cacheProvider = mock.DynamicMock<ICacheProvider>();
MyBasicObjectService service = new MyBasicObjectService(cacheProvider, repo);
cacheProvider.Expect(p => p.Get<MyBasicObject>(Arg<string>.Is.Equal("AnUniqueName"), Arg<Func<MyBasicObject>>.Is.NotNull))
.WhenCalled(call =>
{
var repoCall = (Func<MyBasicObject>)call.Arguments[1];
repoCall.Invoke();
});
repo.Expect(c => c.GetByName("AnUniqueName"));
mock.ReplayAll();
// Act
var result = service.GetByName("AnUniqueName");
// Assert
mock.VerifyAll();
}
}
This works specifically for my use case (invoking a database retrieval in case of a cache miss, and making sure the service uses the correct repository call at that time), but is sort of a not-so-great work-around if you're not planning on invoking the anonymous function right away. I'm sure there are other alternatives with .WhenCalled, but for right now, this is working for me.
I am trying to verify the method i am tested has been invoked with a particular expression. I have spent hours on this without the result i wanted.
This is the System under test
public class sut
{
private IEntityUtil _ew;
public sut(IEntityUtil ew)
{
_ew = ew;
}
public void Search()
{
Guid id = Guid.Parse("CB594050-3845-4EAF-ABC5-34840063E94F");
var res = _ew.SelectSingle<Post>(w => w.Id == id, new PersonalSiteEntities());
}
}
This is the dependency
public interface IEntityUtil
{
TEntity SelectSingle<TEntity>(Expression<Func<TEntity, bool>> predicate, System.Data.Objects.ObjectContext ctx)
where TEntity : EntityObject;
List<TEntity> SelectList<TEntity>(Expression<Func<TEntity, bool>> predicate, System.Data.Objects.ObjectContext ctx)
where TEntity : EntityObject;
bool Insert<TEntity>(TEntity entity, System.Data.Objects.ObjectContext ctx)
where TEntity : EntityObject;
}
And this is how i am trying to test it
public class tst
{
[TestMethod]
public void tst1()
{
var cwMock = new Mock<ConsoleApplication1.IEntityUtil>();
Guid id = Guid.Parse("CB594050-3845-4EAF-ABC5-34840063E94F");
//cwMock.Setup(x => x.SelectSingle<ConsoleApplication1.Post>(w => w.Id == id, It.IsAny<System.Data.Objects.ObjectContext>())).Returns(new ConsoleApplication1.Post()).Verifiable();
//cwMock.Setup(x => x.SelectSingle(It.IsAny<Expression<Func<ConsoleApplication1.Post, bool>>>(), It.IsAny<System.Data.Objects.ObjectContext>())).Returns(new ConsoleApplication1.Post()).Verifiable();
Expression<Func<ConsoleApplication1.Post, bool>> func = (param) => param.Id == id;
cwMock.Setup(x => x.SelectSingle<ConsoleApplication1.Post>(func, It.IsAny<System.Data.Objects.ObjectContext>())).Returns(new ConsoleApplication1.Post());
var sut = new ConsoleApplication1.sut(cwMock.Object);
sut.Search();
//cwMock.VerifyAll();
cwMock.Verify(x => x.SelectSingle(func, It.IsAny<System.Data.Objects.ObjectContext>()));
}
}
Please note the second commented setup will make the test pass but it wont let me verify that a specific expression has been passed in.
Thanks in advance.
Two things that will greatly help (us help you) are
Give your test a meaningful name so we know what you're after,
Arrange your test into three areas, and separate by comments or whitespace:
Arrange,
Act,
Assert
This makes it a bit more clear what the action is.
That said, it appears to me that you are trying to assert that ew.SelectSingle was called once when calling sut.Search()?
Also I noticed you're creating the Guid in your test but never doing anything with it. So, here is a quick proposal on your test (not using the IDE so you may find errors):
[Fact]
public void Verify_SelectSingle_IsCalledOnce( ){
Guid id = Guid.Parse( "CB594050-3845-4EAF-ABC5-34840063E94F" );
var cwMock = new Mock<ConsoleApplication1.IEntityUtil>( );
var post = new ConsoleApplication1.Post{ Id = id };
cwMock
.Setup( x=> x.SelectSingle<ConsoleApplication1.Post>(It.IsAny<Guid> ))
.Returns( post );
var sut = new ConsoleApplication1.sut(cwMock.Object);
sut.Search();
cwMock.Verify(
x=> x.SelectSingle( It.IsAny<ObjectContect>( o => o.Id == id )),
Times.Once);
}
As already noted, it's very hard to tell exactly what you're trying to accomplish because you haven't made your test names explicit. That said, it looks like you need to provide a callback to your mocked setup that will allow you to verify the expression. Something like this should help you (using the commented out setup that passes):
cwMock.Setup(x => x.SelectSingle(It.IsAny<Expression<Func<ConsoleApplication1.Post, bool>>>(), It.IsAny<System.Data.Objects.ObjectContext>())).Callback<Expression<Func<ConsoleApplication1.Post, bool>>>(VerifyExpression).Returns(new ConsoleApplication1.Post()).Verifiable();
Then create a callback method
private static void VerifyExpression(Expression<Func<ConsoleApplication1.Post, bool>> expression)
{
var func = expression.Compile();
// call func(params) and verify against it
}
I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided.
Like the code provided below.
public class UserRegistrationProcess : IUserRegistration
{
private readonly IRepository _repository;
private readonly ISmsService _smsService;
public UserRegistrationProcess(IRepository repository, ISmsService smsService)
{
_repository = repository;
_smsService = smsService;
}
public void Register(string phone)
{
var user = new User(phone);
_repository.Save(user);
_smsService.Send(phone, "Welcome", "Message!");
}
}
It is a really simple class but how would you go about and test it?
At the moment im using Mocks but I dont really like it
[Test]
public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
{
var repository = new Mock<IRepository>();
var smsService = new Mock<ISmsService>();
var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);
var phone = "07012345678";
userRegistration.Register(phone);
repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
}
[Test]
public void WhenRegistreringANewUser_ItWillSendANewSms()
{
var repository = new Mock<IRepository>();
var smsService = new Mock<ISmsService>();
var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);
var phone = "07012345678";
userRegistration.Register(phone);
smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once());
}
It feels like I am testing the wrong thing here?
Any thoughts on how to make this better?
Refactoring the mocks out in the way that #Serghei suggests is good.
I also see that the name of the behaviour isn't actually describing the behaviour. I like to use the word "should", as in, "My class should do some stuff".
Your class shouldn't send the user to the database when it's registering a user. It should ask the repository to save the user. That's all. It doesn't know whether the repository sends it to the database, keeps it in memory or nukes it from orbit. It's not your class's responsibility.
By phrasing the behaviour this way, you can explicitly show - and help others understand - where the scope of your class's responsibility ends.
If you rename your method something like WhenRegisteringANewUser_AsksRepositoryToSaveIt() that might make the example you've given feel more natural.
In your case don't need to write
repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
because this method doesn't return a value
you can write
repository.VerifyAll();
Also for smsService it's a good way to use Moq.
look at after some refactor
Mock<IRepository<>> repository;
private Mock<ISmsService> smsService;
const string phone = "0768524440";
[SetUp]
public void SetUp()
{
repository = new Mock<IRepository<>>();
smsService = new Mock<ISmsService>();
}
[Test]
public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
{
var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);
userRegistration.Register(phone);
repository.VerifyAll();
smsService.VerifyAll();
}