junit.framework.AssertionFailedError: Exception occured : java.lang.ClassCastException: - mockito

Getting error
junit.framework.AssertionFailedError: Exception occured : java.lang.ClassCastException: us.ny.state.ij.safeact.ask.persistency.impl.CchResponsePersistenceImpl$$EnhancerByMockitoWithCGLIB$$d62edc51 incompatible with
here is stubbing
private PartnerPersistenceImpl mockPartnerPersistenceImpl;
#Before
public void setUp() throws Exception {
mockPartnerPersistenceImpl = mock(PartnerPersistenceImpl.class);
}
PowerMockito.doReturn(mockPartnerPersistenceImpl).when(PersistenceFactory.class,"getService",any(RecordTypeEnum.class),any(EntityManager.class));
service.processRequest("DUmmy data");
The return type of PersistenceFactory method is
public static ADRBasePersistenceImpl<?, Long> getService(){}
In service class we are type casting to different class to return
PartnerPersistenceImpl parnerPeristenceImpl = (PartnerPersistenceImpl) PersistenceFactory.getService(RecordTypeEnum.SELLERPARTNER, entityManager);
I don't know why mockito not accepting that cast?

Related

Mockito, channel output of void function to System.out?

I have this logging class in my legacy application,
I am trying to Mock it for testing and output all messages from "WriteLog" method to System.out
This is the class
public abstract class LoggingServicesWorker {
public abstract void WriteLog(ELogLevel arg0, int arg1,String arg2,String arg3);
}
This is what I did so far,
I am not sure how to write to System.out
Also How to tell the first argument to have any enum type (ELogLevel)?
LoggingServicesWorker logger = mock(LoggingServicesWorker.class);
Mockito.doNothing().when(logger).WriteLog(ELogLevel.DEBUG,anyInt(),anyString(),Mockito.eq(anyString()));
You can use Mockito#doAnswer for executing side-effects:
doAnswer((invocation -> {
System.out.println(Arrays.toString(invocation.getArguments()));
return null;
}))
.when(worker)
.WriteLog(any(ELogLevel.class), anyInt(), anyString(), anyString());
Standalone class with the default behavior for return values (and usable with Java 7):
class PrintArgsToStdoutAnswer implements Answer<Object> {
private final ReturnsEmptyValues defaultReturn = new ReturnsEmptyValues();
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
System.out.println(Arrays.toString(invocation.getArguments()));
return defaultReturn.answer(invocation);
}
}
...and used in the test method:
doAnswer(new PrintArgsToStdoutAnswer())...

How to mock the custom util class

How can I mock the custom util class? I am getting the error below:
[ERROR] 2019-08-20 12:06:02:197 [] com.metlife.api.clientlibrary.util.JWSRequestUtil.prepareRequestJWS():71 - Exception in preparing JWS request ::
java.lang.NullPointerException: null
The code is:
public class EPartnerPromotionHelperTest {
#InjectMocks
EPartnerPromotionHelper ePartnerPromotionHelper;
#Mock
private JWSRequestUtil jwsRequestUtil;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public void testSavePromotion() throws Exception {
String loggerId = "loggerId";
PromotionDTO promotionDTO = new PromotionDTO();
promotionDTO.setDescription("description");
promotionDTO.setCreationDate(new Date());
promotionDTO.setModifiedDate(new Date());
Mockito.when(jwsRequestUtil.prepareRequestJWS(Matchers.any(EPartnerRestRequestDTO.class)
,Matchers.any(Boolean.class))).thenReturn("test");
PromotionDTO response =ePartnerPromotionHelper.savePromotion(loggerId,promotionDTO);
assertNotNull(response);
}
}
Assuming that the error message comes from the invocation of your prepareRequestJWS method, you can change your syntax and use doReturn instead.
Mockito.doReturn("test")
.when(jwsRequestUtil)
.prepareRequestJWS(Matchers.any(EPartnerRestRequestDTO.class),
Matchers.any(Boolean.class));
Writing it like this the prepareRequestJWS method won't be invoked, check the Overriding a previous exception-stubbing part that is described in the javadoc of the doReturn method. This also applies to normal methods that would throw Exception's when they are invoked.
However a question would be why this exception is coming from your JwsRequestUtil class in the first place. Feel free to add the relevant code to your question.

Error creating bean with name 'securityConfiguration': Unsatisfied dependency expressed through field 'myAppUserDetailsService';

Spring boot 1.5.3 project with test user-registry on H2 in memory DB
This is the Error Stacktrace
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration': Unsatisfied dependency expressed through field 'myAppUserDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'SMRTUserService': Unsatisfied dependency expressed through field 'userInfoDAO'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SMRTUserDAO': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory': Post-processing of FactoryBean's singleton object failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #2 of URL [file:/C:/temp/SMRT/target/test-classes/data.sql]: ....
Can someone help me to understand the problem? I can't solve this errors.
Test Controller
public class CustomerControllerTest extends AbstractControllerTest {
#Test
#WithMockUser(roles = "ADMIN")
public void testShow() throws Exception {
mockMvc.perform(get("/customer/list")
.contentType(APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
}
AbstractControllerTest
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.MOCK)
#AutoConfigureMockMvc
public abstract class AbstractControllerTest extends AbstractTest {
#Autowired protected MockMvc mockMvc;
#Autowired private FilterChainProxy filterChainProxy;
#Autowired private WebApplicationContext webApplicationContext;
#Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
this.mockMvc = webAppContextSetup(webApplicationContext)
.dispatchOptions(true)
.addFilters(filterChainProxy).build();
}
}
SecurityConfiguration
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired private SMRTUserService myAppUserDetailsService;
#Autowired private BCryptPasswordEncoder bCryptPasswordEncoder;
#Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myAppUserDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
}
}
SMRTUSerService
#Service
#Slf4j
public class SMRTUserService implements UserDetailsService {
#Autowired private ISMRTUserDAO userInfoDAO;
#Autowired private SMRTUserRepository smrtuserRepository;
...
}
Thanks
Well, your Exception already explains pretty well what the problem is:
Failed to execute SQL script statement #2 of URL [file:/C:/temp/SMRT/target/test-classes/data.sql]: ....
I asume you're importing some test data for your tests? There must be an error in your SQL statements.
if you are using keycloak for the authentification . you might get this error .
jhipster by default gives you 8090 as auth server , so you have to change it
Solution : 1 - start your keycloak server
2 - go to your jhipster project main->ressources->config->application.yml
change issuer ui by the port where your keycloak server is running : for example : issuer-uri: http://localhost:8080/auth/realms/demo
hope that was helpfull

Throwing Custom Exceptions in Groovy

I am trying to throw a custom exception but no exception is thrown in spock test.
Class A{
static class B extends Exception{
}
public Object getObject() throws B{
if(condition 1){}
else if(condition 2){}
else if(condition 3){ throw new A.B()}
}
}
But no exception is thrown when condition matches
I am using gradle to setup build environment and Spring framework

Compilation error while passing method argument to inline interface implementation

Have a look on the following Groovy code example:
class PersonCreator {
static void main(String[] args) {
println createPerson('Smith')
}
static createPerson(String aLastname) {
new Person() {
final String firstname = 'John'
final String lastname = aLastname
}
}
}
interface Person {
String getFirstname()
String getLastname()
}
When I try to run it exception is thrown
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: aLastname for class: PersonCreator
The exact same code runs fine with Groovy 2.3.2, but with version 2.3.3 and above it fails. Should I raise a bug in Groovy JIRA or is it a feature?
EDIT: for some reason the above example compilation with #CompileStatic added fails with Error:(1, 1) Groovyc: [Static type checking] - Unimplemented node type

Resources