1

I am trying to mock a dbWriteService Method that returns a aggregate exception when i call it, even though everything is not null. I am farely new to mocking and rhino mock, so I do not really get the problem.

This is the part I want to mock in the function i want to test:

public async Task<bool> SaveDataAsync(object data) { ... await _dbWriteService.UpdateAsync(data); ... } 

I am mocking the writeService like this:

dbWriteService = MockRepository.GenerateStub<IDbWriteService>(); dbWriteService.Expect(service => service.UpdateAsync(null)); var wasSaved = subject.SaveDataAsync(data).Result; dbWriteService.AssertWasCalled(service => service.UpdateAsync(null)); 

and i am getting an exception like this:

System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object. at ClearingDataRepository.<SaveDataAsync>d__28.MoveNext() in ....\ClearingDataRepository.cs:line 170 --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task`1.get_Result() at UnitTests.Services.ClearingDataRepositoryTests.SaveDataAsync_Sucess() in ....\ClearingDataRepositoryTests.cs:line 90 

I tried a few things with the mocked function but i do not get the reason why this stuff does not work. Could anybody explain this to me?

1 Answer 1

7

Firstly, you should change GenerateStub to GenerateMock so you can use mock features. Secondly, it would be better to use await instead of .Result() in your test, and the test method return type can be async Task. And thirdly, seems like Rhino Mock wants you to set return value for a mock, which could be set to Task.FromResult(0).

For example, to make sure UpdateAsync was called with null value and final result was true you could write following test with MSTest.

 [TestMethod] public async Task TestMethod1() { // Arrange var dbWriteService = MockRepository.GenerateMock<IDbWriteService>(); dbWriteService.Expect(service => service.UpdateAsync(null)).Return(Task.FromResult(0)); var subject = new Class1(dbWriteService); // Act var result = await subject.SaveDataAsync(null); // Assert Assert.IsTrue(result); dbWriteService.AssertWasCalled(service => service.UpdateAsync(null)); } 

Where Class1 is the class with SaveDataAsync method in my case.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.