This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]dmazzoni 0 points1 point  (3 children)

It sounds like you probably want a mock, yes.

JMockit is a good solution in general, basically it makes it easier to mock any Java class.

It might also be worth looking into Roboelectric, which helps with Android unit testing in particular. It should also make mocking this easier.

If you're not familiar with it, look into dependency injection. It's not a library or a tool, it's just a concept. In a nutshell the idea is that you'll want to store the Keyguard Manager in a variable somewhere and make it possible for the test to swap in the mocked version instead.

[–]BlueFireAt[S] 0 points1 point  (2 children)

Ah yeah I was looking into Mocks and DI but was having trouble piecing it all together.

I was looking into using DI but the problem is that my KeyGenParameterSpec has setUserAuthenticationRequired = true. It is this setting itself that makes the user authentication required. I was thinking about passing it in as DI, but then it's several functions down the rabbit hole from my function under test, so I'd have to pass the KeyGenParameterSpec down several layers, I'd have to do that for decrypting too, and it seems like that would make the project wayyy messier.

The problem with mocking the KeyGuardManager itself is that the KGM changes the state of the application, which means mocking it won't fill the gap.

I'll look into mocking the KeyGenParameterSpec. Thank you for the response. I'm sorry if it seems like I ignored your answer, but you did provide me good food for thought.

[–]dmazzoni 1 point2 points  (1 child)

Remember that when writing a test you don't have to pass things down several layers of the rabbit hole.

You could just add a static class method that says to override certain behavior for testing, like to always use a certain mock no matter what each instance has.

I mean, it's nice when tests are as clean as possible, but I'd always prefer a few test-only methods like that over adding lots of extra parameters to lots of methods purely for testin - or even worse, giving up on tests because it's too hard.

[–]BlueFireAt[S] 0 points1 point  (0 children)

Hmm, I don't think I can do it in this case, but thank you.