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
Related
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.
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());
i am using spring cloud's eureka and feign to communicate between some services (lets say A and B). Now id like to unittest my service layer of a single service (A). The problem is, that this service (A) is using a feign client to request some information of the other service (B).
Running the unittests without any special configuration throws the following exception: java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: service-b => but i do not want any server to run.
My question is: Is there a way to mock the feign client, so i can unittest my service (A) without running an eureka instance and service (B)?
Edit:
I ended up creating a stub for the feign client. The stub is marked as a primary component to force spring instantiating the stub within my tests.
This is the solution i came up with.
//the feign client
#FeignClient("user")
public interface UserClient {
UserEntity getUser();
}
//the implementation i use for the tests
#Component
#Primary //mark as primary implementation
public class UserClientTestImpl implements UserClient {
#Override public UserEntity getUser() {
return someKindOfUser;
}
}
The question is ... do you even need to mock? I often see that people mention "mock" as the first solution to anything that "should not be part of the unit test". Mocking is a technique, not the solution to everything. (see here).
If you are still at the early stages of your code, just refactor and use something else instead of depending on the concrete instance of the Feign Client. You might use an interface, an abstract class, a trait or whatever you want. Don't depend on the object itself, otherwise you have to "mock it".
public interface IWebClient {
public String get(...);
public String post(...);
}
To the question: but I will have other code that will do exactly the same (except that it will be on the concrete instance of Feign), what do I do then?
Well, you can write a functional test and call an instance of a web server that you can setup locally - or use Wiremock, as mentioned by Marcin Grzejszczak in one of the answers.
public class FeignClientWrapper implements IWebClient {
private feign = something
public String get() {
feign.get( ... )
}
public String post() {
feign.post( ... )
}
}
Unit tests are used to test algorithms, if/else, loops: how units work. Don't write code to make mocks fit - it must be the other way around: your code should have less dependencies, and you should mock only when you need to verify the behavior (otherwise you can use a stub or a fake object): do you need to verify the behavior? Do you need to test that a particular method gets called in your code? Or that a particular method gets called with X, Y, and Z for 3 times in a row? Well, then yes, mocking is ok.
Otherwise, use a fake object: what you want is to test just the call/response and maybe the status code. All you probably want is to test how your code reacts to different outputs (e.g., the field "error" is present or not in a JSON response), different status codes (assuming that the Client documentation is right: 200 OK when GET, 201 when POST, etc).
Mocking a feign client is really useful in microservice component tests. You want to test one microservice without having to start all the other microservices.
If you're using Spring (and it looks like you are), the #MockBean annotation together with a bit of Mockito code will do the job.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment =
SpringBootTest.WebEnvironment.DEFINED_PORT)
public class TestYourComponent {
#Configuration
#Import({YourConfiguration.class})
public static class TestConfiguration {
}
#MockBean
private UserClient userClient;
#Test
public void someTest()
{
//...
mockSomeBehavior();
//...
}
private void mockSomeBehavior() {
Mockito.doReturn(someKindOfUser).when(userClient).getUser();
}
}
If you need to use a mock you can use Wiremock to stub the response for a given request - http://wiremock.org/stubbing.html. That way you will do integration tests with real HTTP requests sent. For unit testing the answer from #Markon is very good.
I have a business rule visual studio class library (.NET 2.0) project that takes a dependency on Dynamics Crm Web Services - a classic SOAP web reference as opposed to a WCF endpoint. I want to unit test those business rules without having a real crm instance behind it. Adding a web reference doesn't produce an interface that I can fake. It does generate c# in my project that I think I can fake if I can create the interface. I don't think I need to actually navigate HTTP and get into all of the protocol stuff.
I saw Joh Skeet's blog post. Alas I didn't want to write any code and I'm hoping a tool has been written since then that might help. I tried some of his steps but concluded that he is smarter than me and I couldn't make that work.
I am aware of SoapUI, however, I was hoping for pure unit tests that would work in a CI build environment.
Is there a way to do this.
The standard way to mock something which doesn't come with an interface, is to build your own wrapper around it.
the code you want to mock, say the webservice stuff:
class AutoGeneratedStuff
{
public string GeneratedMethodYouUse()
{...}
public string GeneratedMethodYouDontNeed()
{...}
}
you then make an interface which covers only the bits of the code you need:
public interface IWebServiceClient
{
string MethodYouUse();
}
and a concrete wrapper class which implements it, which has a dependency to the generated stuff
class WebServiceClient : IWebServiceClient
{
private AutoGeneratedStuff _stuff;
public WebService(AutogeneratedStuff stuff)
{
_stuff = stuff;
}
public string MethodYouUse()
{
return _stuff.MethodYouUse();
}
}
then, in your code when you would have called the generated class, call your interface instead. In your unit tests, you can mock the interface, either using a mocking framework, or by implementing the interface with another concrete class that has no dependencies to the generated stuff
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.