When using Ninject for dependeny injection is it best practices to use Ninject in your unit tests or use a mocking framework - unit-testing

I am using ninject to inject dependencies in my production environment. I see two options when it comes to writing unit tests. I can either create concrete classes and inject them using ninject, Or I can use a mocking framework like just mock.
My thought process is to just use both and have the deciding factor be whether or not the TestInterface can be constructed in a reusable way. This way we dont waste time writing the same Mocked method to return an empty list over and over again.
Is there a best practice for this type of thing?

With unit tests on class, it doesn't make a lot of sense to include the DI container in the "system under test" (SUT).
by principle, a class unit test should test the class and the class only
usually you can't "reuse" the bindings in the unit test, you have to create them unit-test specific. Therefore you're only re-testing ninject, but not how you're applying it. Ninject is already tested. So no real benefit for you.
If you do acceptance testing / unit testing on component or application level, then it makes perfectly sense to include Ninject in the SUT.
For a class-level unit test one usually takes a dynamic proxy based mocking framework like MOQ or FakeItEasy.
given an implementation:
public interface IDependency {
void Foo(string bar);
}
public class SomeClass
{
private readonly IDependency dependency;
public SomeClass(IDependency dependency)
{
this.dependency = dependency;
}
public void SomeMethod(string arg)
{
this.dependency.Foo(arg);
}
}
a test would look like (xUnit flavor):
public class SomeClassTest
{
private readonly Mock<IDependency> dependency;
private SomeClass testee;
public SomeClassTest()
{
this.dependency = new Mock<IDependency>();
this.testee = new SomeClass(this.dependency.Object);
}
[Fact]
public void SomeMethod_MustPassArgumentToFoo()
{
const string expectedArgument = "AnyArgument;
this.testee.SomeMethod(expectedArgument);
this.dependency.Verify(x => x.Foo(expectedArgument));
}
}

JustMock has NInject built into it plus a mocking container based on it.
Injecting mocks of dependencies is done automatically when you fetch the instance for the first time:
var container = new MockingContainer<ClassUnderTest>();
var testee = container.Instance;
Plus, you can use NInject's syntax for fine-grained control of the injection behavior, as well as JustMock's syntax for configuring mock behavior.

Related

How can I use .NET Core FirebaseAdminSdk for Unit Testing with Moq

I have been working on .NET Core FirebaseAdminSdk. I want to write unit tests for my own services that are using FirebaseApp class.
FirebaseApp is a sealed class and there is not any interface to moq it.
Is there any way to mock FirebaseApp instance?
private readonly Mock<IFirebaseApp> firebaseApp = new Mock<IFirebaseApp>();
I need an interface something like this.
It's generally not a good idea to try to mock sealed classes like FirebaseApp, because they are designed to be used in a specific way and mocking them can lead to unexpected behavior and make it difficult to test your code correctly.
Instead of trying to mock FirebaseApp, you can use a technique called "dependency injection" to make it easier to test your code. Here's how it works:
Create an interface that defines the methods and properties that you need from FirebaseApp. For example:
public interface IFirebaseApp
{
string Name { get; }
FirebaseAppOptions Options { get; }
Task<string> GetAccessTokenAsync(bool forceRefresh);
void Delete();
}
Modify your code to accept an instance of IFirebaseApp through its
constructor or a property, rather than creating a new instance of
FirebaseApp directly. This is called "dependency injection".
In your unit tests, create a mock implementation of IFirebaseApp
using a mocking framework like Moq. Then pass an instance of the
mock to your code when you create an instance of your service.
This will allow you to easily control the behavior of FirebaseApp in your tests, and make it easier to test different scenarios.

Testing NUnit Startup Azure Function

I want to put Unit Test to this class with NUnit, how do I do it?
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Universal.DataTransferNCFDGII.Function.Services;
[assembly: FunctionsStartup(typeof(Universal.DataTransferNCFDGII.Function.Startup))]
namespace Universal.DataTransferNCFDGII.Function
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<IInsertData, InsertData>();
}
}
}
Generally you do not test classes and methods Startup and Configure as there is no real logic of yours in need of testing. You would just be testing that the dependency injection setup works and that is not your code. It is a good practice while writing tests to remember to only test your code, not third party or .NET libraries. It would be better to cover this with an integration test, rather than unit test.
If you are concerned with no test for this class and method impacting your code coverage, you can just put the ExcludeFromCodeCoverage attribute on your method or class, like this:
[ExcludeFromCodeCoverage]
public override void Configure(IFunctionsHostBuilder builder)

How to decide what to mock in Java Unit Tests?

I am trying to write a Unit Tests to a legacy code using Mockito.
But I am not able to understand how do I mock it. Can some please help.
The real problem I am facing is actually I am not able to decide how to make a decision on what exactly is to be mocked? Below is the code. I have looked at numerous videos on YouTube and read many Mockito Tutorials but all of them seem to be guiding mostly about how to use the Mockito Framework.
The basic idea of what to Mock is still unclear. Please guide if you have a better source. I do understand that the code showed below does not really showcase the best coding practice.
public class DataFacade {
public boolean checkUserPresent(String userId){
return getSomeDao.checkUserPresent(userId);
}
private SomeDao getSomeDao() {
DataSource dataSource = MyDataSourceFactory.getMySQLDataSource();
SomeDao someDao = new SomeDao(dataSource);
}
}
Well, a Unittest, as the name implies, tests a unit. You should mock anything that isn't part of that unit, especially external dependencies. For example, a DAO is normally a good example for something that will be mocked in tests where the class under tests uses it, because otherwise you would really have actual data access in your test, making it slower and more prone to failure because of external reasons (for example, if your dao connects to a Datasource, that Datasource's target (for example, the database) may be down, failing your test even if the unit you wanted to test is actually perfectly fine). Mocking the DAO allows you to test things independently.
Of course, your code is bad. Why? You are creating everything in your method by calling some static factory method. I suggest instead using dependency injection to inject the DAO into your facade, for example...
public DataFacade(SomeDao someDao) {
this.someDao = someDao;
}
This way, when instantiating your DataFacade, you can give it a dao, which means, in your test you can give it a mock, for example...
#Test
public void testSomething() {
SomeDao someDaoMock = Mockito.mock(SomeDao.class);
DataFacade toTest = new DataFacade(someDaoMock);
...now you can prepare your mock to do something and then call the DataFace method
}
Dependency injection frameworks like Spring, Google Guice, etc. can make this even easier to manage, but the first step is to stop your classes from creating their own dependencies, but let the dependencies be given to them from the outside, which makes the whole thing a lot better.
You should "mock" the inner objects that you use in your methods.
For example if you write unit tests for DataFacade->checkUserPresent, you should mock the getSomeDao field.
You have a lot of ways to do it, but basically you can make getSomeDao to be public field, or get it from the constructor. In your test class, override this field with mocked object.
After you invoke DataFacade->checkUserPresent method, assert that checkUserPresent() is called.
For exmaple if you have this class:
public class StudentsStore
{
private DbReader _db;
public StudentsStore(DbReader db)
{
_db = db;
}
public bool HasStudents()
{
var studentsCount = _db.GetStudentsCount();
if (studentsCount > 0)
return true;
else
return false;
}
}
And in your test method:
var mockedDb = mock(DbReader.class);
when(mockedDb.GetStudentsCount()).thenReturn(1);
var store = new StudentsSture(mockedDb);
assertEquals(true,store.HasStudents());

How to unit test a class that consumes a web service?

I have a class (lets call it A) that:
In the constructor takes a config and based on it, creates a stub of
a web service and stores a reference to it in a private field.
Has a few methods that call web methods and some stuff inbetween.
I started to create a unit test that:
Creates an instance of a class A with a dummy configuration.
Through reflection it injects the mocked web service stub.
Although that web service has plenty of methods.
Should I mock them all (in every test, with different data)?
Or maybe I should create another layer that encapsulates only the web methods that are being used?
Or there is another approach?
You should create a wrapper interface around your webservice, and make your class under test take a dependency on that interface, rather than directly on the webservice; you can then mock the interface. Only make that interface expose the methods of the webservice that you find interesting. This is known as a facade pattern, and is detailed here.
Without having a clue about what you're testing, aim for something like this:
public interface IWebserviceWrapper
{
Whatever DoStuff(int something);
}
public class WebserviceWrapper : IWebserviceWrapper
{
private WebService _theActualWebservice;
public WebserviceWrapper(Webservice theService)
{
_theActualWebService = theService;
}
public Whatever DoStuff(int something)
{
return _theActualWebservice.DoSomething(something);
}
}
Then your test would look like this (in this case, using MOQ)
public void Test_doing_something()
{
Mock<IWebserviceWrapper> _serviceWrapperMock = new Mock<IWebserviceWrapper>();
_serviceWrapperMock.SetUp(m => m.DoStuff(12345)).Returns(new Whatever());
var classUnderTest = new ClassUnderTest(_serviceWrapperMock.Object);
var result = classUnderTest.Dothings(12345);
Assert.Whatever....
}
Short answer Yes :). Long answer you should use some kind of mocking lib for example: http://code.google.com/p/mockito/ and in your unit test mock the WS stub and pass it to the tested class. That is the way of the force :)
When you unit test a class, you always want to make sure to only test that class and not include its dependencies. To do that, you will have to mock your WS to have it return dummy data when methods are called. Depending on your scenarios, you do not have to mock ALL the methods for each test, I would say only those that are used.
For an example about mocking, you can read this article: http://written-in-codes.blogspot.ca/2011/11/unit-tests-part-deux.html

How to cleanly unit test a custom ValueResolver ResolveCore(...) method

I'm trying to unit test a custom ValueResolver (Automapper) but am running into problems because the method it forces me to override is not exposed directly in the custom object we must create. I override the protected method "ResolveCore" but the only public method exposed is "Resolve" which expects a complex "ResolutionResult" automapper object as it's input. In the vein of true unit testing I want to test this object / method in isolation to anything else and don't really want to go the route of firing up automapper with mappings to do this test. Likewise it's not possible to Mock "ResolutionResult" and it seems a very complex object to setup for each test (again requiring creation / association of other Automapper objects).
The only (less than ideal) solution I can come up with (and have seen suggested when Googling for a solution) is to stub a public method inside the class that exposes the protected overriden method. If we must go down this route then so be it, but has anyone else got a better solution that tests the method call in isolation doesn't require a modification of the object we are trying to test?
Example code:
public class CustomResolver : ValueResolver<Supplier, string>
{
protected override string ResolveCore(Custom source)
{
return string.Format("{0} {1}", source.Name, source.Descripton);
}
public string UnitTestStub(Custom source)
{
return ResolveCore(source);
}
}
I wouldn't place a public stub in your class. Instead, I'd just create a simple subclass in my unit test assembly that exposes the call I wanted to test:
public class TestCustomResolver : CustomResolver
{
public string TestResolveCore(Custom source)
{
return this.ResolveCore(source);
}
}
Some of this depends on the unit testing framework you're using too. For example, you could use the InternalsVisibleTo() attribute to expose your internals to your unit tests. However, I would lean towards a simple subclass in your unit tests.