Can I call this a stub in JUnit testing? - junit

code -
#Test
public void testAddition() {
Mockito.when(adder.add(Mockito.anyInt(),Mockito.anyInt())).thenReturn(22); //is this stub
Integer result = calculator.add(Integer.valueOf(10), Integer.valueOf(12));
assertEquals(Integer.valueOf(22),result);
}
in the above code can i call below line as stub or test stub
Mockito.when(adder.add(Mockito.anyInt(),Mockito.anyInt())).thenReturn(22); //is this stub
If not, what is the technical term for this line, there should definitely be some.
Thanks in advance.

Yes, you can call that line a stub or test stub.
As we know that a stub is a fake class that comes with preprogrammed return values.
A stub basically is injected into the class under test to give absolute control over what's being tested as input.
And this line does that actually.

Related

How to skip static validation in JUnit test with Mockito

I have a function I need to test:
#Override
public ResponseEntity<BasicResponse> myFunction(HttpServletRequest request, #RequestBody Dto dto, BindingResult result) {
try {
ValidationUtils.invokeValidator(validator, dto, result);
if (result.hasErrors()) {
// do things
} else {
//do things
}
} catch (Exception e) {
// catch
}
//return things;
}
But when I test the function it always go to the catch because of the validator, it says:
"Validator does not support Dto".
I don't care about the validation, I need to test what's inside the try, so I try to use doNothing to skip the validation but I get an error because it's void:
#Test
void TestMyFunction() {
doNothing().when(ValidationUtils.invokeValidator(validator, dto, result));
ResponseEntity<BasicResponse> response = controller.myFunction(request, dto, result);
// assert something
}
Any idea on how to proceed? I can't change the function, I can only write the test and I'm new at this. Thank you.
If ValidationUtils was an object instance that is a Mockito spy or mock, you would be able to mock it like so:
doNothing()
.when(validationUtils)
.invokeValidator(validator, dto, result);
This, unfortunately, does not seem to be the case in your test - ValidationUtils seems to be a class on which a static method is called, which Mockito can handle since version 3.4.0 (before that it was usually handled by PowerMock). thenAnswer should be used with the mockedStatic object instance, similarly to this answer, since the method's return type is void.
An important additional (but mandatory) note: mocking static methods is discouraged and should be avoided whenever possible. It slows down the tests and is a sign of bad design of the classes. The validator should be injected into the class or created using a factory, thanks to that a mocked object instance could be easily used.
I've checked that and in fact the thenAnswer part is not required to do nothing after using mockStatic on a class.
try (var mockedStatic = Mockito.mockStatic(ValidationUtils.class)) {
// test code
}
The code above makes ValidationUtils do nothing and return default values (0, false, null).
See this example (all tests pass).

Mock a statement by using MockIto

I want to write a test method for a service method. In this service method we are calling a query that fetch the data from database and that value is used in the function to do some processing. I want to stub only this db call. here is my function
public arraylist retrieveSomthing(JdbcTemplate){
//some processing is happening
List<Map<String,Object>> result = JdbcTemplate.queryForList("QueryName");
//some processing is happening for the result return from the query.
}
I want to write the test for the above function but I want to stub only the Jdbc.queryforList statement.
Please help me How to go stub the statement.
Thanks in Advance.
#Test
public void testRetrieveSomthing() {
JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class);
List < .. > results = ///something you would do dummy return
when(jdbcTemplate.queryForList(anyString())).thenReturn(results);
List < .. > alist = instance.retrieveSomthing(jdbcTemplate);
assertEquals(alist, expectedList);
}
It's easy to do
1) Mock the jdbctemplate object like below:
#Mock private JdbcTemplate jdbcTemplate;
2) Since jdbcTemplate.queryForList("QueryName") returns list, make sure that you have created a List object and returning that value while stubbing (like below)
List<Example> result = new ArrayList();
result.add("dummy values");
result.add("dummy values");
then
//import static org.mockito.Matchers.anyString;
Mockito.when(jdbcTemplate.queryForList(anyString()).thenReturn(result);
PS: Points to remember while mocking and stubbing are,
1) while dealing with List objects create new object and return as on-stubbing value of actual test class
2) Use matchers like anyString() instead of using some text.
Hope it is useful.

Why I can verify static method for 20 times and it doesn't fail?

That's my test code:
public void testApplyListWhenAddTheSameIDThenReturnDuplicateEntityException(){
MyEntity entityRCM = createMyEntity(AGE_ID, WEIGHT_ID, 0L);
entityModel.addEntity(entityRCM);
MyEntity entityOPC = createMyEntity(DIFF_AGE_ID, WEIGHT_ID, 0L);
EntityCreate create = new EntityCreate(entityOPC);
List<EntityChange> changeList = new ArrayList<EntityChange>();
changeList.add(create);
try {
entityModel.apply(changeList);
fail();
}catch(DuplicateEntityException e) {
PowerMockito.verifyStatic(times(20));
LogManager.error(Mockito.<Logger>anyObject(),Mockito.anyString(),Mockito.<DuplicateEntityException>anyObject());
}
}
The problem is here:
PowerMockito.verifyStatic(times(20));
LogManager.error(Mockito.<Logger>anyObject(),Mockito.anyString(),Mockito.<DuplicateEntityException>anyObject());
I want to verify a static method error in class LogManager, but how can I verify this method for twenty times but it doesn't fail.
Solved in the comments:
Did you add #PrepareForTest and mockStatic? If not, then you may have set up your matchers and static call but PowerMock never sees the actual call to mock before your test completes.
For context, PowerMock mocks static classes by intercepting the classloader and loading a replacement class that calls PowerMock-provided implementations instead of the originals. Unless you add the right preparation, PowerMock won't replace the class, so it won't count static method calls or identify the method to verify, and the test will complete before the verification call ever actually happens.

Webdriver test Script Does not stop after assert failure

In my webdriver script I have the three methods
setup, test and tearDown
following the junit convention.
In the test method I have few asserts like this
#Test
public void testStudentHome() throws Exception {
String classCode = "I6OWW";
Utilities.studentSignin(driver, baseUrl);
assertEquals(true, sth.openNotification());
assertEquals("My Scores", sth.myScores(true));
}
The sth is the PageObject on which I am performing the tests and that I have created in the setup method.
I am calling all these three methods from a main method like this:
public static void main(String[] args) {
StudentHomeTest sht = new StudentHomeTest();
try {
sht.setup();
sht.testStudentHome();
sht.tearDown();
} catch (Exception ex) {
Logger.getLogger(StudentHomeTest.class.getName()).log(Level.SEVERE, null, ex);
sht.tearDown();
}
}
Now while running the test if some assertion fails the test method should (this is what I expect) throw an exception and the main method should call the tearDown method. But this does not happen. and the browser window continues to stay there.
I am using the netbeans ide for running the test.
following the junit convention
If you follow the jUnit convention, then you will know that teardown methods belong in the #After method as this method will always run after your tests.
create a new method with the #After jUnit annotation.
#After
public void tearDown() {
sht.tearDown();
}
Edit
You know what, I believe that you are running into a classic issue of assertEquals in jUnit.
Stolen from this answer...:
JUnit calls the .equals() method to determine equality in the method assertEquals(Object o1, Object o2).
So, you are definitely safe using assertEquals(string1, string2). (Because Strings are Objects)
--
Instead of using assertEquals on these calls, use assertTrue() instead.
assertTrue(sth.openNotification());
assertTrue("My Scores".equals(sth.myScores(true)));
AssertionError doesn't extend Exception - it's a Throwable.
But in any case, you should have
try {
sht.setup();
sht.testStudentHome();
} finally {
sht.tearDown();
}
No need for a catch block. main can throw Exception.

Springmockito stubbing support via XML

I'm trying to use the second example as described on Springockito site:
https://bitbucket.org/kubek2k/springockito/wiki/Home
<mockito:mock id="accountService" class="org.kubek2k.account.DefaultAccountService" />
But how can I stub the Mock so it returns what I want when one of the Mocks getter methods is called? It doesn't seem possible via XML?
You have to inject mock into your test class (#Autowired or #Inject is the easiest way to do that) and stub it just like a normal Mockito mock .
A modified example from a Springockito web page:
#Autowired
private AccountService accountService;
#Test
public void shouldCountInterestForDeposit() {
// given
Deposit deposit = new Deposit(12);
given(accountService.countInterestFor(deposit)).willReturn(1000);
bank.addDeposit(deposit);
// when
bank.endOfTheMonth();
// then
(...)
}