Parallel test with shared mock - unit-testing

I'm writing a unit test class (using testng) that has mocked member variables (using Mockito) and running the tests in parallel. I initially set up the expected mock in an #BeforeClass method, and in each test case I break something by creating a Mockito.when for each exceptional case.
What I'm seeing (unsurprisingly) is that these tests aren't independent; the Mockito.when in one test case affects the others. I noticed that I could be set up the mocks before each test, and I changed the #BeforeClass to #BeforeMethod. I still didn't expect these to pass consistently, as the tests are all still operating on the same shared mock object at the same time. However, all the tests started passing consistently. My question is "why"? Will this eventually fail? No matter what I do (Thread.sleep, etc) I can't reproduce a failure.
Is using #BeforeMethod enough to make these tests independent? If so, can anyone explain why?
Example code below:
public class ExampleTest {
#Mock
private List<String> list;
#BeforeClass // Changing to #BeforeMethod works for some reason
public void setup() throws NoSuchComponentException, ADPRuntimeException {
MockitoAnnotations.initMocks(this);
Mockito.when(list.get(0)).thenReturn("normal");
}
#Test
public void testNormalCase() throws InterruptedException {
assertEquals(list.get(0), "normal"); // Fails with expected [normal] but found [exceptional]
}
#Test
public void testExceptionalCase() throws InterruptedException {
Mockito.when(list.get(0)).thenReturn("exceptional");
assertEquals(list.get(0), "exceptional");
}
}

The problem here is that TestNG creates one instance of your test class ExampleTest and this is the instance that is used by both of your #Test methods.
So when you used #BeforeClass, you would have random failures with testNormalCase() if testExceptionalCase() ran first and altered the state of your test class.
When you changed your annotation to be #BeforeMethod, it would cause the setup to be executed right before every #Test method was executed.
So the setup would fix the state for testNormalCase() which is why it would pass, and since testExceptionalCase() was internally altering the state using Mockito.when() and then running assertions, it would pass all the time as well.
But there's one scenario wherein your setup will still fail, viz., when you use parallel="methods" attribute in your <suite> tag within your TestNG suite xml file i.e., when you configure TestNG and instruct it to run every #Test method in parallel.
In that case, the Mockito.when() within testExceptionalCase() will affect the shared state [ since you are using this in a shared manner amongst all your #Test methods ] causing testNormalCase() to fail randomly.
To fix this, I would suggest that you do the following :
Don't share this between your #Test methods, but house it separately outside of your test class i.e., house all the data members of your test class in a separate pojo which would be mocked rather than mocking this.
Use a ThreadLocal to store the state which is being mocked by Mockito.when() and then run assertions on the ThreadLocal from within your #Test methods.

Related

Mockito Stubbing not working after an exception is stubbed

So, I am trying to unit test a class in various scenarios. We use JUnit V 4.
I have a setUp method wherein i reStub the mock to return an expected mock Value.
I have 4 tests : test1-test4. test1,test2 work fine with the expected mocked value configured in perTestSetup method.
Test t3 needs MockClass to throw an exception, so i configure it seperately in t3. Now t3 works fine as the mock throws the exception as expected.
But when perTestSetup tries to reset the mock to return mockResult before running test4, it fails and throws the same Runtime exception configured in t4. I also tried reset() before mocking in perTestSetup(). But that too fails similarly.
What am i missing here?
#Before
public void perTestSetup(){
when(MockClass.functionCall(...)).thenReturn(mockResult);
}
#Test
public void test1(){
}
#Test
public void test2(){
}
#Test
public void test3(){
when(MockClass.functionCall(...)).thenThrow(new RuntimeExcption());
...
}
#Test
public void test4(){
}
Your perTestSetup() method isn't doing what you think it is doing. The #Before annotation means the test environment will run this method once, before doing any of the tests, rather than once per test. Before I finished reading your question, I was actually itching to advise you to rename this method to simply setup(), as that would be a more accurate description.
Options:
Change the annotation to #BeforeEach, which would then change the behaviour to do what you think it should currently be doing. However, this would be inefficient as in the second two tests you will be defining behaviour and then immediately redefining it.
What do the parameters look like in your functionCall(...)? It may be possible to define two separate behaviours in your single #Before setup() method, i.e.
when(MockClass.functionCall(good values)).thenReturn(mockResult);
when(MockClass.functionCall(bad values)).thenThrow(new RuntimeException());
In each test, call functionCall() with the relevant values for that that particular test.
If the parameters in functionCall() do not readily accommodate the previous approach, consider making two separate instantiations of MockClass, something like
MockClass successfulMockClass = new mock(MockClass.class);
when(successfulMockClass()).thenReturn(mockResult);
MockClass unsuccessfulMockClass = new mock(MockClass.class);
when(unsuccessfulMockClass()).thenThrow(new RuntimeException());
In your tests, call on the relevant mocked object depending on what input you are testing against.
Without being able to see the details of your class, I suspect the second option is what I would go for. It may be worth trying all three to see which feels most intuitive for you, though.

ResourceBundle.getBundle returning actual object in spite of mockStatic and when() directing otherwise

I'm creating tests over existing classes. A number of them have a resource bundle defined as a private final field that's initialized when the object is created via new. I declare a mocked ResourceBundle, use PowerMock's mockStatic method to enable static mocking, and mock the getBundle method to return my mocked ResourceBundle. However, when the constructor runs the code to initialize the field, it simply creates the new resource bundle rather than using the mocked one. I feel like there's one little detail I've missed, but I don't know what it might be.
The reason all this is a problem is this: when I run the test locally, it creates the ResourceBundle object without issue. But when the test is run via our build software (UCBuild), it throws a "can't find resource" exception and the test, and therefore the build, fails.
When I run a test in debug and set a method breakpoint on the constructor, I can see that the "strings" object is created using an actual resource bundle, not the mocked one. I can't for the life of me figure out why.
I've tried declaring the field without initializing it, then using class.getDeclaredField() and Field.setAccesible() to set the resource bundle to point at my mocked one, but of course this just gets overwritten if I run code that re-initializes the field.
The WorkerTest class which tests Worker.java:
#RunWith(PowerMockRunner.class)
#PrepareForTest({FacesContext.class, SaveStatus.class, FacesMessage.class, ResourceBundle.class})
public class WorkerTest {
#Mock
private ResourceBundle mockRB;
#Before
public void setUp() throws Exception {
PowerMockito.mockStatic(ResourceBundle.class);
PowerMockito.when(ResourceBundle.getBundle(anyString())).thenReturn(mockRB);
PowerMockito.when(mockRB.getString(anyString())).thenReturn("tst");
sut = new Worker(); // Breakpoint here to verify mockRB exists
}
...some tests
}
Worker.java:
#Named
#ApplicationScoped
public class Worker implements Serializable {
private static final long serialVersionUID = 4075799125164038417L;
private final ResourceBundle strings = ResourceBundle
.getBundle("com.resources.strings");
public Worker() { //method breakpoint here
}
Thanks in advance
Found the problem. Adding Worker.class to the #PrepareForTest annotation line and everything worked fine.

Clarity regarding performing unit test in Spring Boot Application

I got off from writing basic unit tests using JUnit for simple methods that adds two numbers. I can verify the result by using the assert* family of function calls. Now I want to unit test a Spring Boot controller.
Here is the example of the unit test class -
public class MyJunitTest {
private MockMvc mockMvc;
#Mock
private MyService service;
#InjectMocks
private MyController controller;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
#Test
public void unitTestGetAssessmentDetails() {
when(service.getTest(Someobject.class)).thenReturn(customObjectWithValues);
Results results = controller.getCall(someRequestObject);
assertEquals(results, someOtherObjectPrefilledWithValues);
}
}
My question is, if I know the values set in customObjectWithValues, then someOtherObjectPrefilledWithValues is also set by me, then assertEquals will always give a pass to the test, right? It's essentially testing if 1==1 kind of test. So what is the point of doing these unit tests? I know that the service object should not connect to the actual DB, and hence we are mocking it. So what is the point of doing these tests? Am I missing the bigger picture here as to how to view unit tests?
P.S. - Please feel free to remove this question if it violates the rules of this forum.
Your test verifies that getCall returns the expected results;
this is a black box test.
Since you are writing a unit test,
this is only sufficient to "pretend" to perform a unit test.
This technique is common in firms that conflate code quality with
unit test code coverage.
A better technique is to identify the steps that will be taken by the controller class and to verify that each was executed (perhaps in the correct order, as well).
I will assume that MyController.getCall looks something like this:
#Autowired
private MyService myService;
public BlammyReturnValueType getCall(final BlammyRequestType request)
{
final BlammyReturnValueType returnValue;
returnValue = myService.someServiceMethod(request);
return returnValue;
}
In this case,
I would add the following to the unitTestGetAssessmentDetails test method:
... The current stuff including the assert.
Mockito.verify(service, times(1)).someServiceMethod(customObjectWithValues);
This will confirm that the service method was called exactly one time,
which is correct in this example.
Ok so, unit testing is more about testing the logic written in your function/controller/service. Now, your function might be very simple or it might be very complex. For ex, your function might be taking and UserId in request, connect to database, gets the data and return it and since you are mocking the database connection, you might feel like if you are passing the mocked object as database response, you will obviously get the same response, so what's the point of testing. It might seem correct to not test at all in this case. But let me give you another example, say you have a very complex function, which takes some UserId, gets the whole year data of users banking history, cumulates it and calculates the amount user earned for this year. Now, think how complex this function is. Now since you have mocked the DB connection you will pass in some data, a lot of computation goes on inside and gives the user an amount earned as Interest on saving. Now, for a given mocked data, you know the answer should come as some X amount. Now, over the time, someone made a mistake (maybe subtracted something which was needed to be added). Now, when you run the test. This test will fail and you know something is wrong with logic. Not here you are not directly expecting the output to be equal to your mocked data, some computation has been done over the data, so to verify after each change that function logic is correct, you need to write a unit test to verify it. Now if you see here, your are not testing 1==1 but something different. This is why people write unit tests, to check their logic inside a unit of code.
Hope this helps.
Usually we have 3 layers which are Controller, Service, Repository (DAO if you prefer). I usually do not test controllers because I do not put any logic in them, I just define the endpoint and call the service. The service is what I heavily unit test so you would inject the mocks into your service. Then you would mock your Repository so it wouldn't try to connect to a database.
#InjectMocks
private MyService service;
#Mock
private MyRepository myrepo
#Test
public void unitTestGetAssessmentDetails() {
when(myrepo.find(someInt)).thenReturn(customObjectWithValues);
Results results = service.serviceMethod(someRequestObject);
assertEquals(results, someOtherObjectPrefilledWithValues);
}
Since controllers are supposed to have no logic they shouldn't need unit test because as you correctly say it's a 1==1 test. But they would be tested by integration tests

How to mock this callback using Mockito?

I have this production code in my Presenter:
#UiThread
public void tryToReplaceLogo(String emailInitiallySearchedFor, String logoUrl) {
if(isTheEmailWeAskedApiForStillTheSameAsInTheInputField(emailInitiallySearchedFor)){
if (!TextUtils.isEmpty(logoUrl)) {
downloadAndShowImage(logoUrl);
} else {
view.displayDefaultLogo();
}
}
}
public void downloadAndShowImage(String url) {
final Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
view.displayLogoFromBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(view.getViewContext()).load(url).resize(150, 150).centerInside().into(target);
}
And this unit test for it:
#Test
public void testDisplayLogoIfValidUrlReturnedAndEmailEnteredIsTheSame() throws Exception {
when(loginView.getUserName()).thenReturn(VALID_EMAIL);
when(loginView.getViewContext()).thenReturn(context);
loginLogoFetcherPresenter.onValidateEmailEvent(createSuccessfulValidateEmailEvent(VALID_EMAIL));
waitForAsyncTaskToKickIn();
verify(loginView).displayLogoFromBitmap((Bitmap) anyObject());
}
However, the displayLogoFromBitmap method is never called so my test fails. I need to mock the Target dependency to invoke the onBitmapLoaded method but I don't know how.
Possibly I need to create a static inner class that implements Target so that I can set a Mocked implementation of that in my tests, but how do I invoke the onBitmapLoaded method on the mock?
EDIT:
I have a setter field for Picasso in my LoginPresenter now. In production, (as I am using AndroidAnnotations), I instantiate it in
#AfterInject
void initPicasso() {
picasso = Picasso.with(context):
}
In my test, I mock Picasso like so:
#Mock
Picasso picasso;
#Before
public void setUp() {
picasso = mock(Picasso.class, RETURNS_DEEP_STUBS);
}
(I don't remember why, but I can't use Mockito 2 at this point. It was some incompatibility with something, I think)
In my test case, I got to this point and I don't know what to do:
#Test
public void displayLogoIfValidUrlReturnedAndEmailEnteredIsTheSame() throws Exception {
when(loginView.getUserName()).thenReturn(VALID_EMAIL);
when(loginView.getViewContext()).thenReturn(context);
when(picasso.load(anyString()).resize(anyInt(), anyInt()).centerInside().into(???)) // What do I do here?
loginLogoFetcherPresenter.onValidateEmailEvent(createSuccessfulValidateEmailEvent(VALID_EMAIL));
waitForAsyncTaskToKickIn();
verify(loginView).displayLogoFromBitmap((Bitmap) anyObject());
}
I need to mock the Target dependency
No; do not mock the system under test. Target is as much a part of that system as anything; you wrote the code for it, after all. Remember, once you mock out a class, you commit to not using its implementation, so trying to mock Target to invoke onBitmapLoaded is missing the point.
What's going on here is that you're passing Target—which is real code you wrote that is worth testing—into Picasso, which is external code you didn't write but do depend on. This makes Picasso the dependency worth mocking, with the caveat that mocking interfaces you don't control can get you into trouble if they change (e.g. a method turns final).
So:
Mock your Picasso instance, and the RequestCreator instance Picasso returns when it loads. RequestCreator implements the Builder pattern, so it's a prime candidate for Mockito 2.0's RETURNS_SELF option or other Builder pattern strategies.
Pass the Picasso instance into your system under test, rather than creating it using Picasso.with. At this point you may not need to stub LoginView.getViewContext(), which is a good thing as your test can interact less with hard-to-test Android system classes, and because you've further separated object creation (Picasso) from business logic.
Use an ArgumentCaptor in your test to extract out the Target method that was called on RequestCreator.into.
Test the state of the system before the async callback returns, if you'd like. It's optional, but it's definitely a state your system will be in, and it's easy to forget to test it. You'd probably call verify(view, never()).onBitmapLoaded(any()).
Call target.onBitmapLoaded yourself. You have the target instance at this point, and it should feel correct to explicitly call your code (that is written in your system-under-test) from your test.
Assert your after-callback state, which here would be verify(view).onBitmapLoaded(any()).
Note that there is an existing test helper called MockPicasso, but it seems to require Robolectric, and I haven't reviewed its safety or utility myself.

Running TestNG test sequentially with time-gap

I have couple of DAO unit test classes that I want to run together using TestNG, however TestNG tries to run them in parallel which results in some rollbacks failing. While I would like to run my Unit Test classes run sequentially, I also want to be able to specify a minimum time that TestNG must wait before it runs the next test. Is this achievable?
P.S. I understand that TestNG can be told to run all the tests in a test class in a SingleThread, I am able to specify the sequence of method calls anyway using groups, so that's not an issue perhaps.
What about a hard dependency between the 2 tests? If you write that:
#Test
public void test1() { ... }
#Test(dependsOnMethods = "test1", alwaysRun = true)
public void test2() { ... }
then test2 will always be run after test1.
Do not forget alwaysRun = true, otherwise if test1 fails, test2 will be skipped!
If you do not want to run your classes in parallel, you need to specify the parallel attribute of your suite as false. By default, it's false. So I would think that it should run sequentially by default, unless you have some change in the way you invoke your tests.
For adding a bit of delay between your classes, you can probably add your delay logic in a method annotated with #AfterClass. AFAIK testng does not have a way to specify that in a testng xml or commandline. There is a timeout attribute but that is more for timing out tests and is not probably what you are looking for.
For adding delay between your tests i.e. test tags in xml, then you can try implementing the ITestListener - onFinish method, wherein you can add your delay code. It is run after every <test>. If a delay is required after every testcase, then implement delay code in IInvokedMethodListener - AfterInvocation() which is run after every test method runs. You would need to specify the listener when you invoke your suite then.
Hope it helps..
Following is what I used in some tests.
First, define utility methods like this:
// make thread sleep a while, so that reduce effect to subsequence operation if any shared resource,
private void delay(long milliseconds) throws InterruptedException {
Thread.sleep(milliseconds);
}
private void delay() throws InterruptedException {
delay(500);
}
Then, call the method inside testing methods, at end or beginning.
e.g
#Test
public void testCopyViaTransfer() throws IOException, InterruptedException {
copyViaTransfer(new File(sourcePath), new File(targetPath));
delay();
}