Rectangle 27 17

This worked out for me. I'm only using JUnit and I was able to mock up the Log class without any third party lib very easy. Just create a file Log.java inside app/src/test/java/android/util with contents:

public class Log {
    public static int d(String tag, String msg) {
        System.out.println("DEBUG: " + tag + ": " + msg);
        return 0;
    }

    public static int i(String tag, String msg) {
        System.out.println("INFO: " + tag + ": " + msg);
        return 0;
    }

    public static int w(String tag, String msg) {
        System.out.println("WARN: " + tag + ": " + msg);
        return 0;
    }

    public static int e(String tag, String msg) {
        System.out.println("ERROR: " + tag + ": " + msg);
        return 0;
    }

    // add other methods if required...
}

This is bloody brilliant. And it dodges the need for PowerMockito. 10/10

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 2

Mockito doesn't mock static methods. Use PowerMockito on top. Here is an example.

@user3762991 Also you need to change your matchers. You cannot use a matcher in the thenReturn(...) statement. You need to specify a tangible value. See more info here

If e,d,v method cannot be mocked, just because of this limitation does mockito become unusable?

If you cannot eat a fork, does it become unusable? It simply has another purpose.

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 2

Mockito doesn't mock static methods. Use PowerMockito on top. Here is an example.

@user3762991 Also you need to change your matchers. You cannot use a matcher in the thenReturn(...) statement. You need to specify a tangible value. See more info here

If e,d,v method cannot be mocked, just because of this limitation does mockito become unusable?

If you cannot eat a fork, does it become unusable? It simply has another purpose.

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 2

This worked out for me. I'm only using JUnit and I was able to mock up the Log class without any third party lib very easy. Just inside app/src/test/java/android/util create a file Log.java with contents:

public class Log {
    public static int d(String tag, String msg) {
        System.out.println("DEBUG: " + tag + ": " + msg);
        return 0;
    }

    public static int i(String tag, String msg) {
        System.out.println("INFO: " + tag + ": " + msg);
        return 0;
    }

    public static int w(String tag, String msg) {
        System.out.println("WARN: " + tag + ": " + msg);
        return 0;
    }

    public static int e(String tag, String msg) {
        System.out.println("ERROR: " + tag + ": " + msg);
        return 0;
    }

    // add other methods if required...
}

This is bloody brilliant. And it dodges the need for PowerMockito. 10/10

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 13

The builtin __import__ can be mocked with the 'mock' library for more control:

# Store original __import__
orig_import = __import__
# This will be the B module
b_mock = mock.Mock()

def import_mock(name, *args):
    if name == 'B':
        return b_mock
    return orig_import(name, *args)

with mock.patch('__builtin__.__import__', side_effect=import_mock):
    import A
import B

def a():
    return B.func()

A.a() returns b_mock.func() which can be mocked also.

b_mock.func.return_value = 'spam'
A.a()  # returns 'spam'

Has anyone confirmed this works? I'm seeing import_mock get called for the import A, but not for anything it imports.

ImportError: No module named '__builtin__'

python - How to mock an import - Stack Overflow

python mocking python-import
Rectangle 27 186

var request = new Mock<HttpRequestBase>();
// Not working - IsAjaxRequest() is static extension method and cannot be mocked
// request.Setup(x => x.IsAjaxRequest()).Returns(true /* or false */);
// use this
request.SetupGet(x => x.Headers).Returns(
    new System.Net.WebHeaderCollection {
        {"X-Requested-With", "XMLHttpRequest"}
    });

var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);

var controller = new YourController();
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
Request.Headers["X-Requested-With"]
Request["X-Requested-With"]
Request.IsAjaxRequest()

I get the message "The Type argument for method 'ISetupGetter<T, TProperty>Moq.Mock<T>.SetupGet<Tpropert>.... cannot be infered from uage. Try specifying the type arguments explicitly. What type do I set 'var request=' to though to get this to work?

The problem is that IsAjaxRequest() is static extension method and cannot be mocked - I've updated my answer.

should be context.SetupGet(x => x.Request).Returns(request.Object); your code above is missing the 's' on Return still Also results in Exception System.ArgumentException: System.ArgumentException : Invalid setup on a non-overridable member: x => x.Headers["X-Requested-With"] at Moq.Mock.ThrowIfCantOverride(Expression setup, MethodInfo methodInfo) error message

unit testing - How to mock the Request on Controller in ASP.Net MVC? -...

asp.net-mvc unit-testing mocking rhino-mocks moq
Rectangle 27 28

You cannot mock a final class with Mockito, as you can't do it by yourself.

What I do, is to create a non-final class to wrap the final class and use as delegate. An example of this is TwitterFactory class, and this is my mockable class:

public class TwitterFactory {

    private final twitter4j.TwitterFactory factory;

    public TwitterFactory() {
        factory = new twitter4j.TwitterFactory();
    }

    public Twitter getInstance(User user) {
        return factory.getInstance(accessToken(user));
    }

    private AccessToken accessToken(User user) {
        return new AccessToken(user.getAccessToken(), user.getAccessTokenSecret());
    }

    public Twitter getInstance() {
        return factory.getInstance();
    }
}

The disadvantage is that there is a lot of boilerplate code; the advantage is that you can add some methods that may relate to your application business (like the getInstance that is taking a user instead of an accessToken, in the above case).

In your case I would create a non-final RainOnTrees class that delegate to the final class. Or, if you can make it non-final, it would be better.

+1. If desired, you can use something like Lombok's @Delegate to handle a lot of the boilerplate.

@luigi can you add code snippet for Junit as an Example. I tried to create Wrapper for my final class, but couldn't fiugre out, how to test it.

java - How to mock a final class with mockito - Stack Overflow

java junit mockito
Rectangle 27 31

The following code sample from this Mockito documentation illustrates how to mock a void method:

doThrow(new RuntimeException()).when(mockedList).clear();

// following throws RuntimeException:
mockedList.clear();

Mockito Documentation link is not available now :(

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - How to mock/test method that returns void, possibly in Mockito ...

java testing mocking mockito
Rectangle 27 31

The following code sample from this Mockito documentation illustrates how to mock a void method:

doThrow(new RuntimeException()).when(mockedList).clear();

// following throws RuntimeException:
mockedList.clear();

Mockito Documentation link is not available now :(

java - How to mock/test method that returns void, possibly in Mockito ...

java testing mocking mockito
Rectangle 27 6

I realize I'm a bit late to the party here, but here's a somewhat insane way to automate this with the mock library:

import contextlib
import collections
import mock
import sys

def fake_module(**args):
    return (collections.namedtuple('module', args.keys())(**args))

def get_patch_dict(dotted_module_path, module):
    patch_dict = {}
    module_splits = dotted_module_path.split('.')

    # Add our module to the patch dict
    patch_dict[dotted_module_path] = module

    # We add the rest of the fake modules in backwards
    while module_splits:
        # This adds the next level up into the patch dict which is a fake
        # module that points at the next level down
        patch_dict['.'.join(module_splits[:-1])] = fake_module(
            **{module_splits[-1]: patch_dict['.'.join(module_splits)]}
        )
        module_splits = module_splits[:-1]

    return patch_dict

with mock.patch.dict(
    sys.modules,
    get_patch_dict('herp.derp', fake_module(foo='bar'))
):
    import herp.derp
    # prints bar
    print herp.derp.foo

The reason this is so ridiculously complicated is when an import occurs python basically does this (take for example from herp.derp import foo)

sys.modules['herp']
foo
sys.modules['herp.derp']
ImportError
foo = sys.modules['herp.derp'].foo

There are some downsides to this hacked together solution: If something else relies on other stuff in the module path this kind of screws it over. Also this only works for stuff that is being imported inline such as

def foo():
    import herp.derp
def foo():
    __import__('herp.derp')

python - How to mock an import - Stack Overflow

python mocking python-import
Rectangle 27 16

@RunWith(PowerMockRunner.class)
@PrepareForTest({Log.class})
public class TestsToRun() {
    @Test
    public void test() {
        PowerMockito.mockStatic(Log.class);
    }
}

And you're good to go. Be advised that PowerMockito will not automatically mock inherited static methods, so if you want to mock a custom logging class that extends Log, you must still mock Log for calls such as MyCustomLog.e().

How did you get PowerMockRunner in Gradle??

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 16

@RunWith(PowerMockRunner.class)
@PrepareForTest({Log.class})
public class TestsToRun() {
    @Test
    public void test() {
        PowerMockito.mockStatic(Log.class);
    }
}

And you're good to go. Be advised that PowerMockito will not automatically mock inherited static methods, so if you want to mock a custom logging class that extends Log, you must still mock Log for calls such as MyCustomLog.e().

How did you get PowerMockRunner in Gradle??

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 14

You can put this into your gradle script:

android {
   ...
   testOptions { 
       unitTests.returnDefaultValues = true
   }
}

From Docs: Caution: Setting the returnDefaultValues property to true should be done with care. The null/zero return values can introduce regressions in your tests, which are hard to debug and might allow failing tests to pass. Only use it as a last resort.

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 5

The only thing I can think of is to have the create method on at factory object, which you would than mock.

But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initialization happen together.

java - How to mock object construction? - Stack Overflow

java tdd junit mocking
Rectangle 27 12

You can put this into your gradle script:

android {
   ...
   testOptions { 
       unitTests.returnDefaultValues = true
   }
}

From Docs: Caution: Setting the returnDefaultValues property to true should be done with care. The null/zero return values can introduce regressions in your tests, which are hard to debug and might allow failing tests to pass. Only use it as a last resort.

android - How to mock method e in Log - Stack Overflow

android mockito
Rectangle 27 18

A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.

This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.

To mock a private method directly, you'll need to use PowerMock as shown in the other answer.

@ArtB If the private method is changed to protected there is no more need to create your own mock, since protected is also available into the whole package. (And test sohuld belongs to the same package as the class to test).

@AnthonyRaymond but what if that method is doing something you don't want to be doing in a test? For example, I had some legacy code that was opening a hardcoded local file that was expected to exist in production but not in dev; causing it it die if done in dev. I used this technique to skip the reading of that file.

@ArtB I agree, but the question was "how to mock a private method" that means the class is going to be a mock. so if the method is visibility package, you can mock the method according to what you expect. IMO extending the class instead of mocking is smashing a fly with a hammer.

Thanks, I tried multiple solutions, this is so simple, it's brilliant. Shame on me not thinking the same thing right away.

java - How to mock private method for testing using PowerMock? - Stack...

java testing junit mockito powermock
Rectangle 27 4

(NOTE: On the 4th and 6th line the function returns resolve and reject...

Using $httpBackend inside a controller is a bad Idea since you are mixing concerns inside your Test. Whether you retrieve data from an Endpoint or not is not a concern of the Controller, is a concern of the DataService you are calling.

You can see this more clearly if you change the Endpoint Url inside the service you will then have to modify both tests: the service Test and the Controller Test.

Also as previously mentioned, the use of success and error are syntactic sugar and we should stick to the use of then and catch. But in reality you may find yourself in the need of testing "legacy" code. So for that I'm using this function:

function generatePromiseMock(resolve, reject) {
    var promise;
    if(resolve) {
        promise = q.when({data: resolve});
    } else if (reject){
        promise = q.reject({data: reject});
    } else {
        throw new Error('You need to provide an argument');
    }
    promise.success = function(fn){
        return q.when(fn(resolve));
    };
    promise.error = function(fn) {
        return q.when(fn(reject));
    };
    return promise;
}

By calling this function you will get a true promise that respond to then and catch methods when you need to and will also work for the success or error callbacks. Note that the success and error returns a promise itself so it will work with chained then methods.

A little late to the party but I wanted to share my solution for this. Feel free to disagree with me :)

javascript - Test a controller with success() and error () - Stack Ove...

javascript angularjs unit-testing jasmine
Rectangle 27 210

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance. Note that you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialise these mocks and inject them.

@RunWith(MockitoJUnitRunner.class)
public class SomeManagerTest {

    @InjectMocks
    private SomeManager someManager;

    @Mock
    private SomeDependency someDependency; // this will be injected into someManager

     //tests...

}

java - Difference between @Mock and @InjectMocks - Stack Overflow

java unit-testing mocking mockito
Rectangle 27 117

Mocks as stubs

Mock objects are useful when you want to test interactions between a class under test and a particular interface.

For example, we want to test that method sendInvitations(MailServer mailServer) calls MailServer.createMessage() exactly once, and also calls MailServer.sendMessage(m) exactly once, and no other methods are called on the MailServer interface. This is when we can use mock objects.

With mock objects, instead of passing a real MailServerImpl, or a test TestMailServer, we can pass a mock implementation of the MailServer interface. Before we pass a mock MailServer, we "train" it, so that it knows what method calls to expect and what return values to return. At the end, the mock object asserts, that all expected methods were called as expected.

This sounds good in theory, but there are also some downsides.

If you have a mock framework in place, you are tempted to use mock object every time you need to pass an interface to the class under the test. This way you end up testing interactions even when it is not necessary. Unfortunately, unwanted (accidental) testing of interactions is bad, because then you're testing that a particular requirement is implemented in a particular way, instead of that the implementation produced the required result.

Here's an example in pseudocode. Let's suppose we've created a MySorter class and we want to test it:

// the correct way of testing
testSort() {
    testList = [1, 7, 3, 8, 2] 
    MySorter.sort(testList)

    assert testList equals [1, 2, 3, 7, 8]
}


// incorrect, testing implementation
testSort() {
    testList = [1, 7, 3, 8, 2] 
    MySorter.sort(testList)

    assert that compare(1, 2) was called once 
    assert that compare(1, 3) was not called 
    assert that compare(2, 3) was called once 
    ....
}

(In this example we assume that it's not a particular sorting algorithm, such as quick sort, that we want to test; in that case, the latter test would actually be valid.)

In such an extreme example it's obvious why the latter example is wrong. When we change the implementation of MySorter, the first test does a great job of making sure we still sort correctly, which is the whole point of tests - they allow us to change the code safely. On the other hand, the latter test always breaks and it is actively harmful; it hinders refactoring.

Mock frameworks often allow also less strict usage, where we don't have to specify exactly how many times methods should be called and what parameters are expected; they allow creating mock objects that are used as stubs.

sendInvitations(PdfFormatter pdfFormatter, MailServer mailServer)
PdfFormatter
testInvitations() {
   // train as stub
   pdfFormatter = create mock of PdfFormatter
   let pdfFormatter.getCanvasWidth() returns 100
   let pdfFormatter.getCanvasHeight() returns 300
   let pdfFormatter.addText(x, y, text) returns true 
   let pdfFormatter.drawLine(line) does nothing

   // train as mock
   mailServer = create mock of MailServer
   expect mailServer.sendMail() called exactly once

   // do the test
   sendInvitations(pdfFormatter, mailServer)

   assert that all pdfFormatter expectations are met
   assert that all mailServer expectations are met
}

In this example, we don't really care about the PdfFormatter object so we just train it to quietly accept any call and return some sensible canned return values for all methods that sendInvitation() happens to call at this point. How did we come up with exactly this list of methods to train? We simply ran the test and kept adding the methods until the test passed. Notice, that we trained the stub to respond to a method without having a clue why it needs to call it, we simply added everything that the test complained about. We are happy, the test passes.

But what happens later, when we change sendInvitations(), or some other class that sendInvitations() uses, to create more fancy pdfs? Our test suddenly fails because now more methods of PdfFormatter are called and we didn't train our stub to expect them. And usually it's not only one test that fails in situations like this, it's any test that happens to use, directly or indirectly, the sendInvitations() method. We have to fix all those tests by adding more trainings. Also notice, that we can't remove methods no longer needed, because we don't know which of them are not needed. Again, it hinders refactoring.

Also, the readability of test suffered terribly, there's lots of code there that we didn't write because of we wanted to, but because we had to; it's not us who want that code there. Tests that use mock objects look very complex and are often difficult to read. The tests should help the reader understand, how the class under the test should be used, thus they should be simple and straightforward. If they are not readable, nobody is going to maintain them; in fact, it's easier to delete them than to maintain them.

  • Try using real classes instead of mocks whenever possible. Use the real PdfFormatterImpl. If it's not possible, change the real classes to make it possible. Not being able to use a class in tests usually points to some problems with the class. Fixing the problems is a win-win situation - you fixed the class and you have a simpler test. On the other hand, not fixing it and using mocks is a no-win situation - you didn't fix the real class and you have more complex, less readable tests that hinder further refactorings.
  • Try creating a simple test implementation of the interface instead of mocking it in each test, and use this test class in all your tests. Create TestPdfFormatter that does nothing. That way you can change it once for all tests and your tests are not cluttered with lengthy setups where you train your stubs.

they often encourage bad practices, testing implementation details, hinder refactoring and produce difficult to read and difficult to maintain tests

A well thought out answer, and I mostly agree. I would say that since unit tests are white-box testing, having to change the tests when you change the implementation to send fancier PDFs may not be an unreasonably burden. Sometimes mocks can be useful way to quickly implement stubs instead of having a lot of boiler plate. In practice it does seem that their use is not retricted to these simple cases, however.

isn't the whole point of a mock is that your tests are consistent, that you don't have to worry about mocking on objects whose implementations are continually changing possibly by other programmers each time you run your test and you get consistent test results?

Very good and relevant points (especially about tests fragility). I used to use mocks a lot when i was younger, but now i consider unit test that heavilly depend on mocks as potentially disposable and focus more on integration testing (with actual components)

"Not being able to use a class in tests usually points to some problems with the class." If the class is a service(e.g. access to database or proxy to web service), it should be considered as an external dependancy and mocked/stubbed

@MichaelFreidgeim Why mock database? Why not use an embedded database to test the same thing? That way you don't have separate unit and integration tests. Also your tests perform faster as required because the database is embedded.

unit testing - When should I mock? - Stack Overflow

unit-testing language-agnostic mocking