mocking interview questions
Top mocking frequently asked interview questions
How can I mock my location on a physical device (Nexus One)? I know you can do this with the emulator in the Emulator Control panel, but this doesn't work for a physical device.
Source: (StackOverflow)
Are there any libraries or methods to mock out the file system in C# to write unit tests? In my current case I have methods that check whether certain file exists and read the creation date. I may need more than that in future.
Source: (StackOverflow)
I'd like to test an abstract class. Sure, I can manually write a mock that inherits from the class.
Can I do this using a mocking framework (I'm using Mockito) instead of hand-crafting my mock? How?
Source: (StackOverflow)
I have an interface with a method that expects an array of Foo:
public interface IBar {
void DoStuff(Foo[] arr);
}
I am mocking this interface using Mockito, and I'd like to assert that DoStuff() is called, but I don't want to validate what argument are passed - "don't care".
How do I write the following code using any(), the generic method, instead of anyObject()?
IBar bar = mock(IBar.class);
...
verify(bar).DoStuff((Foo[])anyObject());
Source: (StackOverflow)
Is there a way to have a stubbed method return different objects on subsequent invocations? I'd like to do this to test nondeterminate responses from an ExecutorCompletionService. i.e. to test that irrespective of the return order of the methods, the outcome remains constant.
The code I'm looking to test looks something like this.
// Create an completion service so we can group these tasks together
ExecutorCompletionService<T> completionService =
new ExecutorCompletionService<T>(service);
// Add all these tasks to the completion service
for (Callable<T> t : ts)
completionService.submit(request);
// As an when each call finished, add it to the response set.
for (int i = 0; i < calls.size(); i ++) {
try {
T t = completionService.take().get();
// do some stuff that I want to test
} catch (...) { }
}
Source: (StackOverflow)
I have myService that uses myOtherService, which makes a remote call, returning promise:
angular.module('app.myService', ['app.myOtherService'])
.factory('myService', [myOtherService,
function(myOtherService) {
function makeRemoteCall() {
return myOtherService.makeRemoteCallReturningPromise();
}
return {
makeRemoteCall: makeRemoteCall
};
}
])
To make a unit test for myService I need to mock myOtherService, such that its makeRemoteCallReturningPromise() method returns a promise. This is how I do it:
describe('Testing remote call returning promise', function() {
var myService;
var myOtherServiceMock = {};
beforeEach(module('app.myService'));
// I have to inject mock when calling module(),
// and module() should come before any inject()
beforeEach(module(function ($provide) {
$provide.value('myOtherService', myOtherServiceMock);
}));
// However, in order to properly construct my mock
// I need $q, which can give me a promise
beforeEach(inject( function(_myService_, $q){
myService = _myService_;
myOtherServiceMock = {
makeRemoteCallReturningPromise: function() {
var deferred = $q.defer();
deferred.resolve('Remote call result');
return deferred.promise;
}
};
}
// Here the value of myOtherServiceMock is not
// updated, and it is still {}
it('can do remote call', inject(function() {
myService.makeRemoteCall() // Error: makeRemoteCall() is not defined on {}
.then(function() {
console.log('Success');
});
}));
As you can see from the above, the definition of my mock depends on $q, which I have to load using inject(). Furthermore, injecting the mock should be happening in module(), which should be coming before
inject(). However, the value for mock is not updated once I change it.
What is the proper way to do this?
Source: (StackOverflow)
So, I'm creating a mock object as a static variable on the class level like so... In one test, I want Foo.someMethod() to return a certain value, while in another test, I want it to return a different value. The problem I'm having is that it seems I need to rebuild the mocks to get this to work correctly. I'd like to avoid rebuilding the mocks, and just use the same objects in each test.
class TestClass {
private static Foo mockFoo;
@BeforeClass
public static void setUp() {
mockFoo = mock(Foo.class);
}
@Test
public void test1() {
when(mockFoo.someMethod()).thenReturn(0);
TestObject testObj = new TestObject(mockFoo);
testObj.bar(); // calls mockFoo.someMethod(), receiving 0 as the value
}
@Test
public void test2() {
when(mockFoo.someMethod()).thenReturn(1);
TestObject testObj = new TestObject(mockFoo);
testObj.bar(); // calls mockFoo.someMethod(), STILL receiving 0 as the value, instead of expected 1.
}
}
In the second test, I'm still receiving 0 as the value when testObj.bar() is called... What is the best way to resolve this? Note that I know I could use a different mock of Foo in each test, however, I have to chain multiple requests off of mockFoo, meaning I'd have to do the chaining in each test.
Source: (StackOverflow)
I've got a PHPUnit mock object that returns "return value" no matter what its arguments:
// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
->method('methodToMock')
->will($this->returnValue('return value'));
What I want to be able to do is return a different value based on the arguments passed to the mock method. I've tried something like:
$mock = $this->getMock('myObject', 'methodToMock');
// methodToMock('one')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('one'))
->will($this->returnValue('method called with argument "one"'));
// methodToMock('two')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('two'))
->will($this->returnValue('method called with argument "two"'));
But this causes PHPUnit to complain if the mock isn't called with the argument "two", so I assume that the definition of methodToMock('two') overwrites the definition of the first.
So my question is: Is there any way to get a PHPUnit mock object to return a different value based on its arguments? And if so, how?
Thanks in advance!
Source: (StackOverflow)
I am trying to write some unit tests for my ApiController and faced some issues. There is a nice extension method called Request.CreateResponse that helps a lot with generating response.
public HttpResponseMessage Post(Product product)
{
var createdProduct = repo.Add(product);
return this.Request.CreateResponse(HttpStatusCode.Created, createdProduct);
}
Is there any way to mock CreateResponse without using of partial mocks or direct using of "new HttpResponseMessage(...)"?
Source: (StackOverflow)
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:
public abstract class SomeClass()
{
public void SomeMehod()
{
SomeOtherMethod();
}
internal abstract void SomeOtherMethod();
}
I want to test that if I call SomeMethod() then I expect that SomeOtherMethod() will be called.
Am I right in thinking this sort of test is available in a mocking framework?
Source: (StackOverflow)
I have an service AngularJS service written and would like to unit test it.
angular.module('myServiceProvider', ['fooServiceProvider', 'barServiceProvider']).
factory('myService', function ($http, fooService, barService) {
this.somthing = function() {
// Do something with the injected services
};
return this;
});
My app.js file has these registered:
angular
.module('myApp', ['fooServiceProvider','barServiceProvider','myServiceProvider']
)
I can test the DI is working as such:
describe("Using the DI framework", function() {
beforeEach(module('fooServiceProvider'));
beforeEach(module('barServiceProvider'));
beforeEach(module('myServiceProvder'));
var service;
beforeEach(inject(function(fooService, barService, myService) {
service=myService;
}));
it("can be instantiated", function() {
expect(service).not.toBeNull();
});
});
This proved that the service can be created by the DI framework, however next I want to unit test the service, which means mocking out the injected objects.
How do I go about doing this?
I've tried putting my mock objects in the module, e.g.
beforeEach(module(mockNavigationService));
and rewriting the service definition as:
function MyService(http, fooService, barService) {
this.somthing = function() {
// Do something with the injected services
};
});
angular.module('myServiceProvider', ['fooServiceProvider', 'barServiceProvider']).
factory('myService', function ($http, fooService, barService) { return new MyService($http, fooService, barService); })
But the latter seems to stop the service being created by the DI as all.
Does anybody know how I can mock the injected services for my unit tests?
Thanks
David
Source: (StackOverflow)
How can a IoC Container be used for unit testing? Is it useful to manage mocks in a huge solution (50+ projects) using IoC? Any experiences? Any C# libraries that work well for using it in unit tests?
Source: (StackOverflow)
I have a method on an interface:
string DoSomething(string whatever);
I want to mock this with MOQ, so that it returns whatever was passed in - something like:
_mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) )
.Returns( [the parameter that was passed] ) ;
Any ideas?
Source: (StackOverflow)