I have the following simple JUnit configuration; compiling and running the code under Java 6 works fine, but compiling and running under Java 7 hangs the application (both under Ubuntu 10.04 and MS Vista).
public class TextAreaThread extends Thread {
#Override
public void run() {
JUnitCore junitcore = new JUnitCore();
MyListener listener = new MyListener();
junitcore.addListener(listener);
junitcore.run(CheckerTest.class);
listener.testRunFinished(null);
try {
listener.getRiport();
}
catch (BadLocationException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
CheckerTest contains only basic methods annotated with #Test:
#Test
public void checkWellFormed() throws AssertionError {
fail("failed");
}
Any ideas?
Thanks,
krisy
Matthew, the code is as follows:
public class Validator extends JFrame {
public Validator() {
startMenu.addMenuListener(new MenuListener() {
#Override
public void menuSelected(MenuEvent arg0) {
TextAreaThread tframe = new TextAreaThread(textArea, inputXMLPath);
tframe.start();
//some other stuff
Related
I am new to Spring Integration so please forgive and correct me if my question is absurd. I am trying to write Unit test cases for Spring Integration application where I am testing only controller and looking to mock service call.
Test:
#RunWith(PowerMockRunner.class)
#PrepareForTest({HeaderUtils.class})
#PowerMockIgnore({ "javax.management.*", "javax.script.*" })
public class DocMgmtImplTestPower {
private MockMvc mvc;
#InjectMocks
private DocMgmtImpl docMgmtImpl;
#Mock
DocMgmtService docMgmtServiceGateway;
#Mock
SendComnMsgResponse sendComnMsgResponse;
#Before
public void init() {
MockitoAnnotations.initMocks(this); //
mvc = MockMvcBuilders.standaloneSetup(DocMgmtImpl.class).build();
PowerMockito.mockStatic(HeaderUtils.class, new Answer<Map<String, Object>>() {
#Override
public Map<String, Object> answer(InvocationOnMock arg0) throws Throwable {
Map<String, Object> headers = new HashMap<String, Object>();
HeaderInfo headerInfo = new HeaderInfo();
headers.put(BusinessServiceConstants.SERVICE_HEADER, headerInfo);
return headers;
}
});
}
#SuppressWarnings("deprecation")
#Test
public void testMethod() throws Exception {
SpecialFormMsgRequest arg = new SpecialFormMsgRequest();
Map<String, Object> headers = new HashMap<String, Object>();
Mockito.when(docMgmtServiceGateway.specialFormMsg(Mockito.any(SpecialFormMsgRequest.class),
(Matchers.<Map<String, Object>>any()))).thenReturn(new SendComnMsgResponse());
SpecialFormMsgRequest msg = new SpecialFormMsgRequest();
msg.setUiStaticDocFlag("N");
mvc.perform(post("/specialMsg").accept(MediaType.APPLICATION_JSON).content(asJsonString(msg))
.contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Controller:
#Controller
public class DocMgmtImpl implements DocMgmt {
#Autowired
**DocMgmtService docMgmtServiceGateway;** **// I want to mock this service.**
#Override
#RequestMapping(value = "/specialMsg", method = RequestMethod.POST)
#ResponseBody
public SendComnMsgResponse specialMsg(#Valid #RequestBody final SpecialFormMsgRequest specialFormMsgRequest)
throws BusinessException, TechnicalException {
SendComnMsgResponse sendComnMsgResponse = null;
try {
Map<String, Object> headers = HeaderUtils.getHeaders(poBusinessHeader); // PowerMockito working here...
sendComnMsgResponse = **this.docMgmtServiceGateway.specialFormMsg(specialFormMsgRequest, headers);** // docMgmtServiceGateway is getting null...
} catch (Exception exception) {
handleException(exception);
}
return sendComnMsgResponse;
}
}
Gateway.xml:
<int:gateway id="docMgmtServiceGateway" service-interface="group.doc.svc.gateway.DocMgmtService"
default-reply-channel="docReplyChannel" error-channel="docErrorChannel">
<int:method name="sendComnMsg" request-channel="sendComnMsgRequestChannel" />
</int:gateway>
si-chain.xml:
<int:chain input-channel="esDBBISendComnMsgRequestChannel" output-channel="docReplyChannel">
<int:transformer method="formatRequest" ref="esSendComnMsgTransformer"/>
<int:service-activator ref="sendComnMsgActivator" method="sendComnMsg" />
<int:transformer method="parseResponse" ref="esSendComnMsgTransformer"/>
</int:chain>
I am wondering, whether I am doing correct or not. Because DocMgmtService service is an interface and it don't have implementation. After controller call goes to Transformer as configured above. On this setup I have following quetions.
Can I mock DocMgmtService service with same setup if not what will be correct approach.
If yes then how can I mock my service.
Thanks
It depends on exactly what you want to test.
If you mock the interface, all you are testing is your mock stubbing for that interface (pointless).
The framework creates an implementation of the interface which creates a message from the parameters and sends it to the channel.
You should auto wire the gateway into your test and call it.
You can mock any of the downstream components (e.g. sendComnMsgActivator) as needed.
I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}
I am trying to understand throws clause in JAVA , I wrote the following
piece of code:
class check
{
static void demo()
{
System.out.println("Hello\n");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
demo();
}
}
I understand that it won't compile as the exception has to be handled
in the main method and demo() should be defined with specifying a throws
clause for IllegalAccessException.
But when I change the exception to NullPointerException, the same
program compiles and executes:
class check
{
static void demo()
{
System.out.println("Hello\n");
throw new NullPointerException("Demo");
}
public static void main(String args[])
{
demo();
}
}
I have a simple controller test.
route(fakeRequest(routes.Accounts.accounts()).session("sessionref","fakeSession"));
Secured Autheticator looks like this:
public class Secured extends play.mvc.Security.Authenticator {
#Inject
AuthServices authService;
public String getUsername(Http.Context context) {
return authService.checkSession(context);
}
#Override
public Result onUnauthorized(Http.Context context) {
return ok(index.render(formFactory.form(forms.LoginForm.class)));
}
}
How can i mock authService?
I tried to mock with guice bind but this method don't work
#Before
public void setup() {
startPlay();
MockitoAnnotations.initMocks(this);
Module testModule = new AbstractModule() {
#Override
public void configure() {
bind(AuthServices.class)
.toInstance(authServices);
}
};
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new play.ApplicationLoader.Context(Environment.simple()))
.in(Mode.TEST)
.overrides(testModule);
Guice.createInjector(builder.applicationModule()).injectMembers(this);
}
You can read this for testing Play controllers and follow this example for testing with Guice.
For your case it is something like this:
public class MyTest extends WithApplication {
#Mock
AuthServices mockAuthService;
#Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.overrides(bind(CacheProvider.class).toInstance(mockAuthService))
.in(Mode.TEST)
.build();
}
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testAccounts() {
running(provideApplication(), () -> {
RequestBuilder testRequest = Helpers.fakeRequest(controllers.routes.Accounts.accounts()).session("sessionref","fakeSession");
Result result = route(testRequest);
//assert here the expected result
});
}
}
Hi I have custom junit runner
public class InterceptorRunner extends BlockJUnit4ClassRunner {
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface InterceptorClasses {
public Class<?>[] value();
}
public InterceptorRunner(Class<?> klass) throws InitializationError {
super(klass);
}
#Override
public Statement methodInvoker(FrameworkMethod method, Object test) {
InterceptorStatement statement = new InterceptorStatement(super.methodInvoker(method, test));
InterceptorClasses annotation = test.getClass().getAnnotation(InterceptorClasses.class);
Class<?>[] klasez = annotation.value();
try {
for (Class<?> klaz : klasez) {
statement.addInterceptor((Interceptor) klaz.newInstance());
}
} catch (IllegalAccessException ilex) {
ilex.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return statement;
}
#Override
public void run(RunNotifier notifier) {
FailListener listener = new FailListener();
notifier.addListener(listener);
super.run(notifier);
notifier.removeListener(listener);
}
}
and custom listener
public class FailListener extends RunListener {
#Override
public void testFailure(Failure failure) throws Exception {
System.out.println("test fails");
super.testFailure(failure);
}
public void testStarted(Description description) throws Exception {
System.out.println("Test started");
super.testStarted(description);
}
}
How can I log not only System.out.println("test fails"); but also Exception and some other information?
It seems to me that it possible to use failure, but I don't know how to.
The Failure object has a method getException().