jeudi 9 février 2023

Cannot Mock RandomStringUtils Class method random

I am using RandomStringUtils class from apache commons lang3 library. I am facing issue while mocking the random method of it.

below is my example class with simple method generatePassword.

public class Example() {

    public String generatePassword() {
       
     final String randomDevicePass = RandomStringUtils.random(10, "abcdefghijklmnopqrstuvwxyz");
     
     System.out.println(randomDevicePass)
    
     return randomDevicePass;
        
    }

}

below is my Test Class, by which I am running the test case.

@RunWith(MockitoJUnitRunner.class)
public class ExampleTest() {

    @InjectMocks
    private Example Example;
    
    @Mock
    RandomStringutils randomStringutils;

    @Test
    public void givenCharacters_returnStringPassword() {

           Mockito.when(randomStringUtils.random(Mockito.anyInt(),Mockito.anyString())).thenReturn("asdf");

    Assertions.assertEquals("asdf", example.generatePassword());
    }

}

It gives below error:

Misplaced or misused argument matcher detected here:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object 
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
    when(mock.get(any())); // bad use, will raise NPE
    when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:

I am not sure how to mock the Java inbuilt apache commons library class. not sure can we use spy? or something ...can anyone helps me on this ?

Thanks in advance




Aucun commentaire:

Enregistrer un commentaire