4

My class needs a bitmap but mockito's mock context object is not capable of doing that is seems:

    public class PlayerTest {

        @Mock // Mocking the android context class
        Context mMockContext;
        // intantiating object from that mocked class
        Context mContext;

        private Player player;
        private Bitmap playerBitmap;

        private int screenX;
        private int screenY;

        @Before
        public void setupPlayer(){
            playerBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.player);
            player = new Player(mContext, screenX, screenY,playerBitmap);
        }
...
2
  • Are you trying to mock the static decodeResource method, or just trying to mock the result of mContext.getResources?
    – ThrawnCA
    Sep 18, 2017 at 1:32
  • I guess I'm not really trying to mock context Im just want to test the classes methods and I can't instantiate the class without a bitmap. So really my problem is how do I get a bitmap for a local test without needing the Android framework to call context?
    – red888
    Sep 18, 2017 at 1:34

1 Answer 1

7

Can't you just annotate private Bitmap playerBitmap with @Mock?

I can't see the rest of the class, but I presume you're using the Mockito JUnit runner. If not, you'll need to either use that, or call MockitoAnnotations.initMocks(this) in your setup method.

3
  • Yup that worked, just mocked out the bitmap itself. Just curious how does mockito do that? does it pass an actually bitmap file in there?
    – red888
    Sep 18, 2017 at 1:47
  • 2
    It dynamically creates a subclass of Bitmap, with all methods stubbed out by default. I think you'll find that it wouldn't work if the Bitmap class was final.
    – ThrawnCA
    Sep 18, 2017 at 4:39
  • 2
    @red888 Hint: you shouldn't use technology because you can. It seems that you just started using the Mockito framework without any further thinking what this stuff is actually about. Don't do that. You should understand each line that your code contains, and each character on those lines. There is no point in blindly using a framework and writing down "@Mock" ... when you have no clue what this causes at runtime. Thus start doing some research, for example with vogella.com/tutorials/Mockito/article.html
    – GhostCat
    Sep 18, 2017 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.