NSubstitute – mock throwing an exception in method returning Task

Actually, the accepted answer mocks a synchronous exception being thrown, that is not the real async behavior. The correct way to mock is: var myService = Substitute.For<IMyService>(); myService.GetAllAsync() .Returns(Task.FromException<List<object>>(new Exception(“some error”))); Let’s say you had this code and GetAllAsync() try { var result = myService.GetAllAsync().Result; return result; } catch (AggregateException ex) { // whatever, do … Read more

NSubstitute DbSet / IQueryable

This happens because of NSubstitute syntax specific. For example in: ((IQueryable<Blog>) mockSet).Provider.Returns(data.Provider); NSubstitute calls the Provider’s getter, then it specifies the return value. This getter call isn’t intercepted by the substitute and you get an exception. It happens because of explicit implementation of IQueryable.Provider property in DbQuery class. You can explicitly create substitutes for multiple … Read more

How to mock IConfiguration.GetValue

You can use an actual Configuration instance with in-memory data. //Arrange var inMemorySettings = new Dictionary<string, string> { {“TopLevelKey”, “TopLevelValue”}, {“SectionName:SomeKey”, “SectionValue”}, //…populate as needed for the test }; IConfiguration configuration = new ConfigurationBuilder() .AddInMemoryCollection(inMemorySettings) .Build(); //… Now it is a matter of using the configuration as desired to exercise the test //… string value … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)