error compiling junit test with expect exception

I am having difficulty using junit 4's expected annotation to look at exceptions. I can't compile the code because there's an unhandled exception. Here's a simple example that creates the situation: import static org.junit.Assert.*; import java.io.UnsupportedEncodingException; import org.junit.Test; public class Simple { @Test(expected=UnsupportedEncodingException.class) public void simpleTest(){ String a = ""; a.getBytes("UTF-123"); } } I get a compilation e

Junit How to mock a method in PowerMock?

I'm using PowerMock 1.4.12 and JUnit 4.8.1. I'm having a problem getting a method to return the data I want it to. I have @Before public void setUp() throws Exception { ... userService = createMock(UserService.class); loginController.setUserService(userService); … } @Test public final void testAuthenticateForLoggedInAdmin() { authorities.add(adminAuthority); final User user = new User(); user.setUserName("userName"); user.setPassword("password"); user.set

Writing Junits test class for a DoubleClickListener

I need to write a Junit test class for my DoubleClickImplementation class. Here is the code : DoubleClickImplementation.java public class DoubleClickImplementation implements IDoubleClickListener { private TreeViewer treeViewer; public DoubleClickImplementation(TreeViewer viewer) { this.treeViewer = viewer; } /** * Expands and Collapses the tree items. * * @param event * */ @Override public void doubleClick(DoubleClickEvent event) { IStructuredSelection selection = (IStructuredSelection) tre

Junit Dropwizard, Jersey, unit testing - GET throws ConstraintViolationException: The request entity was empty at

I have Dropwizard application and I am writing unit tests for it. I am following Dropwizard's documentation to do so : http://dropwizard.readthedocs.org/en/latest/manual/testing.html What I am missing is how can I add parameter to my test which invokes GET method? Here in the documentation : assertThat(resources.client().resource("/person/blah").get(Person.class)) .isEqualTo(person); What if my get method has a parameter? In Jersey's WebResource there are: @Override

Junit MuleESB Simple Test Case not Working

I have the following simple Mule ESB flow that Ia m trying to write a test case for: <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" basePath="/product-design" doc:name="HTTP Listener Configuration"/> <jms:activemq-connector name="Active_MQ" brokerURL="tcp://localhost:61616" validateConnections="true" doc:name="Active MQ"/> <flow name="product-designFlow"> <http:listener config-ref="HTTP_Listener_Configuration" path="/" allowedMethod

Why is junit timeout annotation not working? Tests hang instead

I've noticed several junit tests hanging, where I would have expected them to fail via the junit timeout mechanism. For example: public static final long TIMEOUT = 20_000L; @Test(timeout = TIMEOUT) ... When the maven build occurs (surefire 2.19), I see tests occasionally hang (forever, until I abort the build...) that I would have thought junit would enforce the timeout for and fail the test, and move on. I was able to get a threaddump of where it seems stuck. Any ideas? "main" #1 prio=5

Junit How to import Jira X-Ray data without creating new tests

My team is just getting started with X-Ray, and we are setting up our pipelines. However, while doing this I noticed that if I submit a Junit xml file to X-Ray via the REST api, it will create new tests for any test data that isn't already in the system. Is there a way to have X-Ray ignore test results for tests that don't exist for the test execution? I don't want it constantly creating extra tests. For example: (Jira/X-Ray Server) TestExecution MyExecution has test testA From client, I submit

JUnit Custom Rules

JUnit 4.7 introduced the concept of custom rules: http://www.infoq.com/news/2009/07/junit-4.7-rules There are a number of built in JUnit rules including TemporaryFolder which helps by clearing up folders after a test has been run: @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); There's a full list of built in rules here: http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/package-summary.html I'm interested in finding out what custom rules are in place where y

How could i get a Testname / Test status in JUnit

I am new to JUnit . I am working on the ways to get a output like classname / function name / status / description. I figured that there is no other way to get success test name other than FrameworkMethod using Rule. Is it possible to set a Rule to a suite which s running with the help of JUnitCore/textui.Thx in advance.!! Edit:- I tried testwatchman with Junit 4.9b2 but executing suites is not working for me. Any help would be appreciated. @RunWith(Suite.class) @SuiteClasses({testclas

Junit JMockit mock protected method in superclass and still test method in real child class

I am still learning JMockit and need help understanding it. I am testing a class that uses superclass methods. My test gets a null pointer when it attempts to use the superclass method due to code inside it that uses struts action context to get the session and pull an object from the session. The method I want to bypass the struts session stuff inside the protected method. public class MyExtendingClass extends MySuperClass{ public void methodIamTesting(){///} } public abstract class My

Basic JUnit test for JavaFX 8

I want to create basic JUnit test for JavaFX 8 application. I have this simple code sample: public class Main extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Tabs"); Group root = new Group(); Scene scene = new Scene(root, 400, 250, Color.WHITE); TabPane tabPane = new TabPane(); BorderPane borderPane = new BorderPane()

Junit Exception while running tests through cassandra-unit

I keep getting this error while running junit tests in maven : com.datastax.driver.core.TransportException: [/127.0.0.1] Channel has been closed It eventually leads to OutOfMemory exception. I am using cassandra-unit to run an embedded cassandra cluster. After a few test cases it starts throwing the following error : java.util.concurrent.ExecutionException: com.datastax.driver.core.TransportException: [/127.0.0.1] Channel has been closed at com.google.common.util.concurrent.AbstractFuture

Junit Spring Retry Not working

I am trying to setup a very simple test to see if I can get Springs Retry API working but it doesn't seem to be working as expected. Below is my code / configuration. I am using Spring 3.0 Spring Retry Version defined in POM.xml <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.1.2.RELEASE</version> </dependency> Interface for class under test public interface RetryTest {

Junit unit test spring controller with WebTestClient and ControllerAdvice

I'm trying to unit test my controller and the specific case which is : my service return a Mono.Empty, I throw a NotFoundException and I wan't to make sure I'm getting a 404 exception here's my controller : @GetMapping(path = "/{id}") public Mono<MyObject<JsonNode>> getFragmentById(@PathVariable(value = "id") String id) throws NotFoundException { return this.myService.getObject(id, JsonNode.class).switchIfEmpty(Mono.error(new NotFoundException())); } Here's my

Junit Grails: Setting datasource bean in applicationcontext in unit Tests

I am using grails 3.2.7 & I am unit Testing a method that has following lines of code: void abc(){ ApplicationContext ctx = Holders.grailsApplication.mainContext def dataSource = ctx.getBean('dataSource') } Inside unit test(JUnit) can anyone please help me with : How to set 'datasource' Bean in applicationContext? I tried: applicationContext.beanFactory.registerSingleton("dataSource", DataSource) But this doesn't work. Can anyone help me here?

Lombok error has occurred when junit running

It works in spring boot or normal projects but it didn't work when junit running I saw many many solutions about lombok but, didn't work for example install lombok plugin in intellij Build, Execution, Deployment -> Compiler -> Annotation Processors -> Enable annotation processing check! import lombok.extern.java.Log; import org.junit.Test; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api

Junit How to import the '@Test' method in Java

I am trying to use the @Test function on a small program as I am directed to using Java 8 tutorial on youtube. Find it here. I am up to lesson 2 which starts at 21:59. Here is the youtube link. https://www.youtube.com/watch?v=grEKMHGYyns However, I have the following errors: When trying to import the Test function the advice given by my Apache Netbeans IDE is ... "package org.junit does not exist" ... the same happens for "org.Assert" Over the "@Test" function on line 9 of my PersonT

Junit Mock a void method called from constructor

I have the following class under test. I need to mock a method call- estabilishConnection from constructor, which returns void. public class ClassToBeTested { private ClassToBeMocked classToBeMocked; private String name; private int age; ClassToBeTested(ClassToBeMocked classToBeMocked, String name){ this.classToBeMocked = classToBeMocked; this.name = name; age = this.getAge(name); this.estabilishConnection(); } private int getAge(String name

Junit Getting Null CallableStatement with Mockito

Hi Actually I have implemented the CallableStatementCreator which is callback for jdbc template I am trying to mock its method but getting the CallableStatement object as null in try resource below is my code could you please let me know why i am getting null. Note if I pass Mockito.anyString() its working but i don't want because spot bugs is throwing below error Bug type SQL_INJECTION_JDBC (click for details) ODR_OPEN_DATABASE_RESOURCE import java.sql.CallableStatement; import java.sql.Connect

Junit Unit-Testing PersistenceLayer (JPA/EclipseLink)

I am not sure what is the correct way of testing my Database, without an prepared In-Memory-Database. I have following TestSuite for JUnit4. Ignore the JpaManager, I just need this, because the application runs as a Eclipse RCP and not in a container, nor Spring is used (yet), so I cannot inject an EntityManager-reference and have to handle it manually. public class CustomerJpaTest { private Customer testCustomer; @Before public void setUp() throws Exception { JpaManager.

Junit PowerMokito doNothing() on private setter NullPointer

Issue: Nullpointer exception thrown when attempting to execute PowerMockito.doNothing(). I need to create a partialMockObject class that will return a private method value and do nothing for another private setter method. I am able to make it work if I replace doNothing() with supress() but would like to figure this out. Code: @Test public void testPowerMockito() throws Exception { final String methodName1 = "Method1"; final String methodName2 = "Method2"; //Using Power

Junit testing void method with EasyMock

I need to test sorting class which takes a array of certain interface type. The interface only has one function which only compare an object and return some int value. I am trying to use easymock to test it with jUnit. I am stuck with two problems. First, I need to assign some value to the each mock object that I created for the given interface. mock[0] = EasyMock.createMock(CompareValue.class); How can I assign some value to mock[0]? The interface CompareValue only has following method: in

Running junit tests in intelliJ in parallel

Is it possible to run junit tests in intelliJ in parallel? If so, how do i do this? I set the "fork" parameter to class level and this didn't do anything - actually, it made everything a bit slower, so i'm unsure what "fork" does that is beneficial? Is it possible to do this just using intelliJ, or do i need some fancy test framework and all the hoo-hah that that would involve? Finally, assuming this is at all possible, can one control the number of forks or threads or whatever they want to c

Junit How to Mock recursive function

When I test a method the inner of the method invokes itself and another method that is in the same class. I use a partial mock to specify the other method's return value but how do I specify the first method's return value?

How to use JunitTest in Spring MVC

I want code a Junit for my project but i have a problem below. This is Junit Test with function loginTest @Test public void loginTest(){ User u = userService.login("User", "123"); assertNull(u); } And it throws the error: //error tunnel: java.lang.NullPointerException...

Junit Assert - Converting two Java objects to XML and make assertions about them as XML

I have to write a Junit test where I have to compare two XML documents . Initially both these documents are Java Objects. I'm not sure how to convert them to XML and compare them? This is the code I have so far: Actual RsActual = exchange.getIn().getBody(Actual.class); ExpectedRs expectedRs = new ExpectedRs(); String newRs=FileUtils.getFileContent("src/test/resources/Test/ExpectedRs.xml"); expectedRs.setXYZField(newRs.toString()); Assert.assertEquals(expectedRs.getXYZField(), RsActual.getXYZFi

Junit Need help in writing test for logger.isDebugEnabled()

Following is the update complete code: public Info verify(final String accessTk) throws AuthenticationException { final Info accessInfo = readAccessToken(accessTk); if (logger.isDebugEnabled()) { logger.debug(accessInfo); } verifyTkExpire(accessInfo); return accessInfo; } I am not aware of the use of logger and thus trying to see a way to test it.

how to mock an instance method invocation from static method while writing junit for static method?

how to mock an instance method invocation from static method while writing junit for static method?I'm writing tests for existing code. class A { public static D methodX() { B b = new B(); C c = b.doSomething(); } } class B { public C doSomething() { return C; } } class Atest { @Test public void testMethodX() { B b =Mockito.mock(B.class); Mockito.when(b.doSomething()).thenReturn(new C()); A.methodX(); // some assertion

How to filter the contents of xml formatter in ant junit task?

I am integrating junit test cases with my current project that uses ant build files. I have added a few test cases, and they are running perfectly as part of build process. I need to generate a detailed and relevant report of junit along with build. Inside <junit>, I am using <formatter>. I am facing following issues: If I use <formatter type="plain">, it contains very limited information. If I use <formatter type="xml>, it prints too many properties. I tried writing a

JUnit Test cases not executing after adding testng dependency in Maven project

We have a maven project which runs fine and execute JUnit test cases. We wanted to generate html reports so we added dependencies for testng, now no test cases are executed, if we remove dependency of testng test cases runs again. Here are all the dependencies. <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.50.1</version> </dependency> <dependency> <

Junit Jacoco: Aggregating branch coverage report of multiple test case method

I am using Ant JUnit. <for list="${test.classes.list}" param="class" delimiter=","> <sequential> <for list="${@{class}}" param="method" delimiter=","> <sequential> <jacoco:coverage destfile="${basedir}/jacoco.exec"> <junit fork="true"> ...... <test name="@{class}" methods="@{method}"/> </junit> </jacoco:coverage> <jacoco:report>

JUnit code coverage not covered completly

I wrote test cases for below class but problem is still its not getting covered 100% and i mentioned not coverage code with > symbol in my below class can some one suggest me what can i do for cover remaining code Repository class public RowMapperServerResponse insertproductDetails(RowMapperServerResponse rowMapperServerResponse) { try { int insertRow = jdbcTemplate.update( "insert into Master_Circuit (id_type,product,seq_no,name,dependen

Create executable jar from JUNIT 5 without maven/gradle

How do I create an executable jar for my JUnit 5 test class without maven/gradle/etc.? If I try Eclipse Junit Class -> Export -> Java -> Runnable Jar the jar file produced will not run, it says main method is needed. However, the testRunner examples I've found online are all for JUnit4 and have compatibility issues with JUnit 5.

Junit Wiremock request not matching even with anyRequestedFor(anyUrl())

I have a java service and using junit 4.x as test framework. I am using the junit @Rule in test file like this: @Rule public WireMockRule wireMockRule = new WireMockRule(12345); This is the test case: @Test public void test() throws MessageException { stubFor(get(urlPathEqualTo("/deal_catalog/v1/lookupId")) .willReturn(aResponse().withBody( "\"deal\": {" + "\"id\": " + dealId.toString() + "}"

Junit Is there a Windowlicker for wxpython?

Having recently read "Growing OO systems guided by tests", I am very impressed with the windowlicker testing utility for java/junit. Basically it wraps the GUI and GUI-interaction with drivers and gestures, so your integration/end-to-end tests can be written neatly like: //setup ui.enterUserDetailsFor(newUser) ui.sendForm() //assert ui.showsWelcomeMessage() All swing-gui-thread synchronization and finding widgets etc is nicely isolated in the framework. Exactly this sort of higher level testi

Junit for JiraRestClient create Issue

I am trying to write a JUnit test for following method which creates a new Jira issue, do anyone know how to mock JiraRestClient or is there any other way to write a test for this My code is public Issue createNewIssue(BasicProject project, BasicUser assignee, BasicIssueType issueType, String summary, String description, String parentKey, File attachment) { try { IssueInputBuilder issueBuilder = new IssueInputBuilder(project, issueType); issueBuilder.setDescription(descri

Inject test data to Junit reports for failed tests (failsafe plugin used)

I have several tests cases in a list using failsafe and Junit as per below: @Test public void testResults() { for (TestCase test : TestCaseList) { int result = test.getActualResult(); int expected = test.getExpectedResult(); if (result != expected) { System.out.println("Failed test " + test.getTestInfo()); } assertEquals(result, expected); } } I want the report something lik

Junit Blueprint - Unit testing with Pax Exam - Unable to resolve the dependencies

We are in process of migrating spring based camel application to blue print based camel application. We are also migrating to fuse 6.1 version. I am using Pax Exam with Junit runner along with apache felix container to perform of my unit testing. I am facing problem on unresolved bundle problem related to ehcache manager. I have tried giving required depencies to pax configuration as mavenBundle but without anyluck. Exception doesn't give detail about missing dependencies instead it gives generi

Junit private fields

Here is an existing class and its method I am trying to mock: public class ClassUndertest{ private Object field_private = new Object(); public Object method_public() { field_private.method(); method_private(); } private Object method_private() { .... return Object; } } My tests partially mocks ClassUndertest: ClassUndertest partialmockinstance = PowerMock.createPartialMock(ClassUndertest.class, "method_private"); When I run mock obje

Junit running testrunner with cucumber

I am having problem running testrunner with cucumber. I need someone to help me check the @CucumberOptions. Thank you package stepDefinition; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith (Cucumber.class) @CucumberOptions (features = "Feature" ,glue={"stepDefinition"}) public class testRunner { }

Junit - program verification vs whitebox fuzzing?

I understand that program verification is a branch of computer engineering - but that it's practical application to real world code bases is limited by combinatorial explosion. I also understand that as part of designing your software change, for a modification to an existing Java framework, it's helpful to think about whitebox, boundary and blackbox tests for your algorithm, in advance. (Some people call this hammock driven development - thinking before you code.) Assuming you take this thi

Which built-in JAR file in Eclipse/RSA deals with creation of Junit Test Suite?

I am unable to find the built in JAR file in Eclipse/RSA that deals with creation of Junit Test Suite: File-> New -> Junit Test Suite We are using RSA 8.0.2 version and with this RSA, currently the Test Suites are created in JUnit3 format by default. I have to modify this existing functionality (creating Junit3 TestSuite) to create Junit4 Test Suites with annotations. Please can anyone help me out on this?

Ignore Junit test from the parent abstract class

I have a big set of unit test that needs to be ignored for a while and alle these unit tests are extending an Abstract class like this: public class MyAbstractTest { @BeforeClass public void init(){ //global init for all unit tests } public void some_parent_methods(){ // some code } } I was thinking just adding the @Ignore on the Abstract will ignore all the sub-tests but it does not to work like this. Is there any way to do it (with Junit 4.x) instead

I am getting a null parameter in the constructor when attempting to use parameters with junit4

Basically, I am attempting to experiment with junit4 parameters. I am not clear why I am getting null as the parameter to the LongMathAddTest constructor. Thanks GC @RunWith(value = Parameterized.class) public class LongMathAddTest { @Parameters public static Iterable<Object[]> data() { Object[][] data = new Object[][]{{new Long[]{1L,3L,4L,5L},1},{new Object[]{2l,3l,6l,78l,90l},30},{new Object[]{3l,78l,4l,3l},4},{new Object[]{4l,545l,56l,3l},3},{new Object[]{

  1    2   3   4   5   6  ... 下一页 最后一页 共 7 页