2

I have an MVC project in ASP.NET CORE. I have added a class library and added testing frameworks in project.json.

The test methods seems to execute and run. But I have scenarios where I need to use shims and stubs.

For example Web Client or a an interface method. I am unable to add fakes for dll's in ASP.NET CORE. How do I do it? Is there any method to shim methods like Web client in core?

Dependencies added:

"dependencies": {
    "NETStandard.Library": "1.6.0",
    "dotnet-test-mstest": "1.0.1-preview",
    "MSTest.TestFramework": "1.0.0-preview"
  },
Kusum
  • 501
  • 2
  • 11
  • 30
Rijas Kb
  • 212
  • 3
  • 10

2 Answers2

2

To create mocks, you can use "Moq": "4.6.25-alpha" package. It works with .NET core and is what the ASP.NET team uses.

Following articles gives an example of how you can use mocks to do unit testing. In the article Xunit is used but it shouldn't be that different with MSTest.

https://docs.asp.net/en/latest/mvc/controllers/testing.html

Also you can take a look at the MusicStore sample's xunit tests: https://github.com/aspnet/MusicStore/tree/1.0.0/test/MusicStore.Test

Kiran
  • 56,921
  • 15
  • 176
  • 161
  • can you provide an example of mocking the webclient or httpclient method which is used to get api data which can be mocked?? – Rijas Kb Jul 05 '16 at 09:44
  • I am not clear. Are you using httpclient or webclient inside of your controller's action? If yes, then you could probably take a look at this : http://stackoverflow.com/a/22264503/1184056 – Kiran Jul 08 '16 at 21:07
  • I am actually using a httpcline tinside the controller to make an api call from an another service hosted outside the domain.. So inorder to fake this , i need some solution.. my controller from which i am using the httpClient is not implemented using an interface or wrapper.. i am asking if there is any possible solution to Shim the httpClient.. – Rijas Kb Jul 11 '16 at 04:51
  • I don't think its possible to shim the httpclient if we look at its type. The earlier link seems to be a good(or maybe the only) solution here. – Kiran Jul 11 '16 at 12:48
  • @KiranChalla, at the moment, there is no nuget package for dotnet-test-mstest that would support NetStandard1.6 - we only have an pre-release version of this library for .NETFramework and .NETCoreApp – ironstone13 Jan 18 '17 at 19:48
1

You can use Flurl instead of currently used HttpClient. It has testing capabilities. http://tmenier.github.io/Flurl/testable-http/, E.g.

using (var httpTest = new HttpTest()) {
        // Flurl is now in test mode 
       sut.CallThingThatUsesFlurlHttp(); // HTTP calls are faked!
}
Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170