Getting a null pointer because Mapper interface not instantiated for Junit Not sure how to fix. Example code bellow,
#Autowired
private Mapper mapper;
Detail newDetail= mapper.map(detail, Detail.class);
Any help would be awesome
I tried instantiating with other maps and it didn’t work.
I found the solution. I used a #Mock injection and mocked the mapper being called like in the main function. This solved the npe.
Related
I'm trying to create tests for my spring-cloud-stream project. I've created my own BizSyncProcessor interface instead of using the default Processor, which seems to be in all the documentation. I've done this kind of project before with tests, but can't remember if I used mockito at the same time, so I'm wondering if that's the issue, because I'm doing #RunWith(MockitoJUnitRunner.class) instead of #RunWith(SpringRunner).
I also had similar problems when building the actual app, before I included the rabbit implementation as a dependency in maven.
IntelliJ flags an error on the #Autowired BizSyncProcessor saying 'no Beans of type 'BizSyncProcessor' could be found. However I'm able to run the test, so it compiles, but then bizSyncProcessor is null when running the test.
I'm including mockito because the handler that listens for the message makes a call to another service (the SFISClient), so I'm mocking out that call.
Here's my test:
#RunWith(MockitoJUnitRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#EnableAutoConfiguration
#Configuration
#EnableBinding(BizSyncProcessor.class)
public class UpdatedBusinessHandlerTest {
#Autowired
private BizSyncProcessor bizSyncProcessor;
#Autowired
private MessageCollector messageCollector;
#Mock
SFISClient sfisClient;
#InjectMocks
UpdatedBusinessHandler updatedBusinessHandler;
#Test
public void testWiring() throws Exception {
UpdatedBusinessAlert updatedBusinessAlert = new UpdatedBusinessAlert();
updatedBusinessAlert.setBusinessId(UUID.randomUUID());
Message<UpdatedBusinessAlert> updatedBusinessAlertMessage = MessageBuilder.withPayload(updatedBusinessAlert).build();
bizSyncProcessor.writeUpdatedBusinessIds().send(updatedBusinessAlertMessage);
Message<BusinessFlooringSummary> businessFlooringSummaryMessage = (Message<BusinessFlooringSummary>) messageCollector.forChannel(bizSyncProcessor.writeFlooringSummaries()).poll();
BusinessFlooringSummary businessFlooringSummary = businessFlooringSummaryMessage.getPayload();
assertNotNull(businessFlooringSummary);
}
}
The #SpringBootTest and everything Spring-based are not going to work in your case because you don't use #RunWith(SpringRunner). There is just nothing what can trigget those Spring hooks.
On the other hand there is no reason to use a MockitoJUnitRunner. You simply can rely on the #MockBean instead for your SFISClient: https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans
I am trying to write a #test in Junit using mockito and powermock. I have no issue stubbing methods that have no parameters. However when I try telling mockedBank to return true no matter what is passed into latePay, I get java.lang.NullPointerException. latePay is a final method that is why I am using powermock. Any suggestions are much appreciated.
BankGenerator mockedBank = PowerMockito.mock(BankGenerator.class);
when(mockedBank.latePay(Matchers.any(MoneyCalculator.class))).thenReturn(true);
Have you added the correct annotations to your class containing the tests?
For example:
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassWithFinalMethod.class)
public class ClassContainingUnitTests {
...
}
I have used PowerMock with EasyMock in the past, and forgetting to include these annotations sometimes resulted in strange results.
For further reference, check here:
http://www.codeproject.com/Articles/806508/Using-PowerMockito-to-Mock-Final-and-Static-Method
Hope this helps.
We are facing one issue in our Mule Adapter related to JAXB context, needed some opinion on the same
We are using xpath to evaluate some expressions in the choice blocks in our adapter like below for instance,
<choice doc:name="Choice">
<when expression="//env:abc/env:Body/ref:dataelement/ref:/ref:element" evaluator="xpath">
......
</when>
Now, this works perfectly fine in our application but the problem arises when one of other team uses this Adapter as a jar in their application.
When they try to use this adapter, they are getting below error,
Message : More than one object of type class javax.xml.bind.JAXBContext registered but only one expected.
Type : org.mule.api.registry.RegistrationException
Code : MULE_ERROR--2
JavaDoc : http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/registry /RegistrationException.html.
After debugging with the help of loggers etc, we narrowed down to the choice block used above which is causing this particular issue. Also, googled a bit and found one of the posts pointing out the same issue.
Also, to confirm we commented out the choice block having xpath expression and the flow went ahead but broke again where was xpath used in some other way.
https://www.mulesoft.org/jira/browse/MULE-5926
Can anyone please suggest any suitable workaround to resolve this issue?
I agree with you. It is an unresolved issue in Mule.
One solution we have implemented is not define the jaxb context in the config you are providing in the jar file.
Along with the jar file, give instructions to the end application using it, to include the JAXB packages in their JAXB Context object definition.
This way there will be only one JAXB context and it will work smoothly.
Hope this helps.
This is a bit late however the solution that worked was
<mulexml:jaxb-context name=“JAXB_Context“ packageNames=“org.example.test1:org.example.test2“ doc:name=“JAXB Context1“ />
Please note that there must be no space between package names.
Thanks to: http://dominikbial.de/quicktipp-working-with-more-than-one-package-name-in-a-jaxb-context-config-in-mule-esb/
As of now we cannot add more than one JAXBContext in mule. As an alternative you can write your custom transformer.
I implemented something like
public interface MyAppJaxbObj2XmlComponent<I,O> extends
MyAppComponent<I,O>,Callable {
public O marshal(I input) throws Exception;
}
Abstart transformer
public abstract class AbstractMyAppJaxbObj2XmlComponent<I,O> implements
MyAppJaxbObj2XmlComponent<I,O>{
private Class<I> inputType;
public AbstractMyAppJaxbObj2XmlComponent(){
this.inputType = (Class<I>) new TypeToken<I>(getClass())
{}.getRawType();
}
public AbstractMyAppJaxbObj2XmlComponent(Class<I> type){
this.inputType = type;
}
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
I input = eventContext.getMessage().getPayload(inputType);
O output = marshal(input);
return output;
}
}
Your flow transformer this will load your needed jaxb during startup.
#Component
public class MyFlowJaxbObj2XmlComponent extends
AbstractMyAppJaxbObj2XmlComponent<RequestPayloadType,String> {
#PostConstruct
public void init() {
//Load your schema during startup
}
}
You can also implement a fluid interface as an alternative for this.
I'm trying to write a simple Spring Boot controller that renders a GORM instance and failing.
Here's a shortened version of my code:
#RestController
#RequestMapping("/user")
class UserController {
#RequestMapping(value='/test', method=GET)
User test() {
return new User(username: 'my test username')
}
}
I get the following error message:
Could not write JSON: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"])
The error seems to be caused by extra properties injected by GORM. What is the proposed solution for this? Will this eventually be solved in gorm-hibernate4-spring-boot? Should I simply disable SerializationFeature.FAIL_ON_EMPTY_BEANS (I don't have a lot of experience with Jackson so I'm not entirely sure what side effects this may have)? Should I use Jackson's annotations to solve the problem? Any other options?
I've found a way to get rid of the error using this code:
#Component
class ObjectMapperConfiguration implements InitializingBean {
#Autowired
ObjectMapper objectMapper
#Override
void afterPropertiesSet() {
def validationErrorsModule = new SimpleModule()
validationErrorsModule.addSerializer(ValidationErrors, new ErrorsSerializer())
objectMapper.registerModule(validationErrorsModule)
}
}
class ErrorsSerializer extends JsonSerializer<ValidationErrors> {
#Override
void serialize(ValidationErrors errors, JsonGenerator jgen, SerializerProvider provider) {
jgen.writeStartObject()
jgen.writeEndObject()
}
}
Obviously this solution is far from perfect as it simply nukes all validation errors but right now it is good enough for me. I am pretty sure the Spring Boot team will have to address this issue eventually as the GORM objects are also being serialized with some internal Hibernate properties like attached. I'm not accepting this answer as it is not an acceptable solution for most scenarios, it basically just squelches the exception.
This did not work for me.
So I used this instead and the error disappeared.
#JsonIgnoreProperties(["errors"])
I'm using springBootVersion '1.4.1.RELEASE' with gorm & hibernate5:
compile("org.grails:gorm-hibernate5-spring-boot:6.0.3.RELEASE")
I am having to include the following at the top of each domain class in order to use them in a client response (i.e. json serialization using jackson):
#JsonIgnoreProperties(["errors", "metaClass", "dirty", "attached", "dirtyPropertyNames"])
When using springBootVersion '1.3.5.RELEASE' I was able to get away with:
#JsonIgnoreProperties(["errors"])
This is trending in the wrong direction :)
I am writing junit test to test BaseClass method. The method uses super class members.
The BaseClass constructor invokes super(arg1, arg2).
In the super(arg1, arg2) constructor there is a dependency injector setting a private member
of the super class.
When I am running the test, since the dependency is not set, the super() is throwing an
exception. I want to mock only that statement in the super() which is setting the private member with dependency injection. How to do with mockito ?
Field injection is always a problem for testing. So whenever you have the choice, choose constructor injection instead.
You could start the dependency injector and make it inject a mock instead of a real class. Solutions would depend on the DI framework that you use actually (guice, cdi, ...) For guice you could use jukito, for cdi Arquillian for example. But it slows down the test execution and adds complexity to your test class.
As a alternative you could reflect the private field on an instance of you test class an simply set a mock. Something like:
instance = new TestObject();
Field injected = TestObject.class.getDeclaredField("injected");
injected.setAccessible(true);
injected.set(instance, mock(InjectedType.class));
while TestObject is the class that you want to test, injected the private field where something is injected an InjectedType the type of that private field.