FAQ Database Discussion Community


Spring: can't load properties on junit with PropertyPlaceholderConfigurer

java,spring,junit,spring-test
Note: I've added the projects described above in a drop file service for easy reproduction and browsing -> http://dropcanvas.com/ujzw5 Only available for 3 days though. Problem: I have a program that works, called SomeBean. Running it I get the expected results and Spring wiring. I'd like to make a...

SpringJUnit4ClassRunner unit test does not work. Error: Failed to load ApplicationContext

java,maven,junit,spring-test,spring-restcontroller
I am very new to Spring. We have Spring Rest API i.e. model, controller and service. Everything works, when I type 'mvn install' it will compile, package and deploy to local weblogic. Problem comes only when I write unit test under com.gm.apms.test and write ExampleControllerTest.java using @RunWith(SpringJUnit4ClassRunner.class) I get error...

Mock class inside REST controller with Mockito

java,testing,junit,spring-boot,mockito
I have a spring-boot application which exposes a REST interface via a controller. This is an example of my controller: @RestController public class Controller { @Autowired private Processor processor; @RequestMapping("/magic") public void handleRequest() { // process the POST request processor.process(); } } I am trying to write unit tests for...

Why is my Spring Boot autowired JPA Repository failing JUnit test?

java,spring,junit,spring-boot
My JUnit test is failing with the following error: "java.lang.IllegalArgumentException: Could not find field [userRepository] of type [null] on target [[email protected]]" Here is the Test class: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = App.class) @WebAppConfiguration @IntegrationTest public class UserResourceTest { @Autowired private UserRepository userRepository; private MockMvc restUserMockMvc; @Before public void setup() { UserResource userResource...

JUnit ExpectedException rule doesn't work

java,junit
I have a method which I should test: public void createNode(String name, String primaryNodeType, String[] mixinNodeTypes) throws RepositoryException { final Node parentNode = this.parentNodeStack.peek(); boolean isParentImport = (name == null && isParentNodeImport); if (name == null) { if (this.parentNodeStack.size() > 1) { throw new RepositoryException("Node needs to have a name.");...

ant LinkageError without includeantruntime

java,ant,junit
How can I prevent the AntClassLoader and URLClassLoader from causing a linkage error? Due to an older project, junit and hamcrest.core are put into ANT_HOME and our build uses includeantruntime=true in order to run unit tests. I am now working on a project built with ant where I don't want...

Java Junit Failure For an Attribute Class

java,junit,enums,get
I have the class Mappa that has mappaName as an attribute (to choose from the enum Name) and a method getMappaName that returns it, when i run a test to compare one of the mappaName chosen from Name i get expected FERMI but was:null public class Mappa { private Name...

JUnit asserting two Strings whether they're equal or not

java,junit,outputstream
So I looked up this question and tried it, but with no success. My code should be testing if the method is correctly outputing the text onto the console by reading it back in using Streams. ByteArrayOutputStream outStream = new ByteArrayOutputStream(); PrintStream myStream = new PrintStream(outStream); System.setOut(myStream); o.doSomething(); //printing out...

Edit app.iml in Android Studio 1.2.1.1

android,intellij-idea,android-studio,junit,robolectric
After 3 days struggling to make JUnit and Robolectric to work with Android Studio I finall did it, but there is one important step I have to make everytime I open the IDE. I have to go to app.iml and change "false" to "true" in "ALLOW_USER_CONFIGURATION". After this the testing...

Testing Expected Exceptions with ActivityInstrumentationTestCase2

android,eclipse,unit-testing,junit
I want to Unit Test this simple activity (Please focus on the onClick() function): public class MainActivity extends Activity implements OnClickListener { private EditText edtValue1; private EditText edtValue2; private TextView txtResult; private Button btnAdd; private Button btnMuliply; private ICalculator calculator; final String LOG_TAG = "MainScreen"; @Override protected void onCreate(Bundle savedInstanceState)...

Is there a way to verify if the Catch part of a try/catch instruction is called in a test method when using JUnit?

java,unit-testing,junit,mockito
For example, if I had the following class that I want to test: public class SomeClass{ public void someMethod() { try { //Some code, where comething could go wrong } catch (Exception err) { //Handling it amounts to logging the problem and trying to continue } } } If I...

Using non-static injected services in JUnit Parameterized Tests

java,junit,guice
I want to use Guice and GuiceBerry to inject a non-static legacy service into a factory class. I then want to inject that factory into my Parameterized JUnit test. However, the issue is JUnit requires that the @Parameters method be static. Example factory: @Singleton public class Ratings { @Inject private...

Why do i need a constructor in an abstract class?

java,testing,junit,junit4
I'm currently working my way through a java tutorial, where i am being introduced to abstract classes and testing with J-Unit. I have 2 files, AthleteTest & BikerTest, with BikerTest extending AthleteTest.AthleteTest contains the common methods and variables of my different tests, while BikerTest contains the specifics. ATHLETETEST import static...

Mocking test class Spring camel

junit,apache-camel,spring-test
I am new to camel. I am trying to write a test case. public class A { private B b; public void update(String s){ //calling some methods on B ..... } } Test class public class TestA extends CamelSpringTestSupport { private ClassPathXmlApplicationContext xmlAppContext; @Test public void testA() { String xml...

idea sbt project when I run test case it does not compile

intellij-idea,junit,sbt
I use JUnit for the test,when I change some codes, I must make project manually, it can't auto compile like maven. If I doesn't make project it is the last time code. Can anybody tell me why? Thanks a lot!

Why android studio 1.2.1.1 automatically only support ONE test file?

java,android,junit,android-testing
I wanted to add two different test files in my project. One for instrumental tests and the other one for junit tests. I have added src/androidTest/java file into my project. Everything worked perfectly, java file changed its color to green, but when I added src/test/java it didn't work. The file...

Gradle configuring TestNG and JUnit reports dirs

testing,junit,gradle
I am relatively new to gradle and we use both JUnit and testNG unit tests in our project. With google help I figured out how to make both testNG and JUnit tests running. Below is how I ended up by achieving it build.gradle .... task testNG(type: Test) { useTestNG {}...

Mock function not found in EasyMock

java,unit-testing,junit,easymock
I am trying to build my first EasyMock test, however I have a trivial problem that the function "mock" is not found. Here is my pretty straightforward code: package homework; import org.easymock.EasyMockSupport; import org.junit.Before; import org.junit.Test; import com.locusenergy.homework.Elevator; public class ElevatorTest extends EasyMockSupport{ private Elevator elevator; @Before public void setUp()...

String condition check failing for test

java,string,junit
I have a method to validate a grouper string: public String validateGrouper(String grouper) { if(grouper!=null) grouper = grouper.trim(); if(grouper==null || grouper.equals("") || !grouper.equalsIgnoreCase("AND") || !grouper.equalsIgnoreCase("OR")) { System.out.println("Trap for grouper validation triggered with grouper: "+grouper); grouper="AND"; } else grouper = grouper.toUpperCase(); return grouper; } I am running it against this test:...

delete method in junit test with spring mvc

java,spring,spring-mvc,junit
I'm making junit test for spring mvc project, I can make test method for get and post methods like the following example for get method,now I need to make test for delete method put I got this error (The method DELETE(String, Long) is undefined for the type myclassTest) this tutorial...

How to use EqualsVerifier in a Spock test

testing,junit,spock,equalsverifier
I have been writing my tests using spock. But to test Equals Hashcode contracts, I am trying to use EqualsVerifier. So my test code looks like: def "test equals hashcode contract"() { EqualsVerifier.forClass(Content.class).verify(); } But this does not look like its running with spock. How can I workaround this? I...

JUnit to test for StringBuffers

java,methods,junit,stringbuffer
Assignment: Write a JUnit test assuming you have two StringBuffer references named sbOne and sbTwo and you only want it to pass if the two references point to the same StringBuffer object. I want to make sure this actually a good way to approach this assignment. I wrote the assumed...

Mock private static final field using mockito or Jmockit

java,junit,mockito,static-members,jmockit
I am using private static final LOGGER field in my class and I want LOGGER.isInfoEnabled() method to return false. How can I mock the static final field by using mockito or jMockit My class is: import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Class1 { private static final Logger LOGGER = LoggerFactory.getLogger(Class1.class);...

Java JUnit4: Make simple assertEquals Test pass

java,junit,junit4
I am trying to make a simple test using assertEquals pass -- in my case: assertEquals(bob,cell.getLifeForm());. The first test assertTrue(success); works, meaning boolean success = cell.addLifeForm(bob); works. But I cannot get assertEquals(bob,cell.getLifeForm()); to pass. I believe I had to add the instance variable LifeForm myLifeForm; so the Cell class can...

Running Jenkins job with multiple browsers

jenkins,junit,nosetests
I am using the combination of Jenkins, python, unittest, nosetests to run test suites. I publish the results in nosetests.xml to Jenkins using Junit plugin. My question: How can I run the same test suites with different browsers (Chrome, FF, IE,…,etc) and publish all the results in the same Jenkins...

Mockito doThrow() not acting as I expect

java,unit-testing,junit,mockito,stubbing
I'm working on my UnitTests related to a project that uses WebDrivers, WebElements and so on. I got pretty far with mocking connections and everything but there is one problem I'm stuck with. I got a try block in my class that looks similar to class MyClass { myMethod() {...

Why JUnit Testing exception always fail? [duplicate]

java,exception,junit
This question already has an answer here: How do you assert that a certain exception is thrown in JUnit 4 tests? 15 answers I'm using JUnit 4.11. Eclipse Version: Luna Service Release 2 (4.4.2) I need do the exception test. The code maybe like this: // src code public...

How to mock web service call without passing mocked class as parameter

web-services,junit,mocking
I have a web serivce class which need to unit tested. Here is class which is under test public class ValidatePaymentMessage { public CsmValidationResultX validatePaymentmsg(String csmName, String base64PayloadXML){ //Call Web Service to validate Payment CsmValidationResultX responseMsg=null; PaymentManagerWebService paymentManagerWebService = new PaymentManagerWebService(); PaymentManagerWebServiceImpl serviceAddrs = paymentManagerWebService.getPaymentManagerWebServicePort(); try { responseMsg = serviceAddrs.validatePayment(csmName,...

Config.properties returns value only when called twice

java,testing,junit
I have a program that I'm running tests for, and I have a particular method that attempts to access a config.properties file value. It returns null the first time I call it, and only returns a value after the second time it's called and I can't figure out why. Here...

Spring MVC testing: How do I check if a model attribute does not exist?

spring,spring-mvc,junit
I’m using Spring 3.2.11.RELEASE. I’m using the new 3.2 mock MVC framework for unit testing, and normally I can check for model attributes using something like the following … private MockMvc mockMvc; … @Test public final void test() { … mockMvc.perform(get(“/mypath”) .param("userId", customerId)) .andExpect(status().isOk()) .andExpect(model().attribute(“attr1”, “value”)) .andExpect(view().name(“my view")); but how...

testing the order of a collection

java,unit-testing,junit,junit4,hamcrest
Given a list of objects I'd like to test that they return in the correct order, but I would like to not assert the entire object. For example I'd like to verify that they're in order by id 1, id 2, id 3, or in another case date mostRecent date...

Using jUnit mock objects with Spring

spring,unit-testing,spring-mvc,intellij-idea,junit
I'm trying to write a unit test for a class that uses Spring. The code itself seems to be fine, but I keep getting a null pointer exception on my When statements for some reason. The source code is as follows: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/spring-bean-config.xml"} public class testClass { @Mock...

Why does Android Studio say “Test events were not received”?

unit-testing,android-studio,junit,gradle,android-gradle
I'm trying to unit test in my android application, and this is the simple test tutorial what i'm doing. import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ServerListManagerTest extends AndroidTestCase{ @Test public void testTrueIsTrue() throws Exception { assertEquals(true, true); } } The directory is like this,...

UnitTest with gradle, when test Infrastructure is in some other project in src/test/java folder

unit-testing,junit,gradle,multi-project
There is two java projects A and B, the build-engine is gradle. That is a multi-project and A depends on B A: build.gradle ... dependencies { compile project (':B') } ... B has core code in src/main/java and test code in src/test/java. Also in src/test/java is some testing infrastructure classes...

jUnit change behavior of a method

java,junit,mocking,powermock
I have to make some jUnit tests for some methods and I can't change the source code. Is there any possibility to change the behavior of a function without change source code? Look a straight-forward example: Class A and B are source code (can't change them). I want to change...

Getting Exception “Failed to load transport: org/mule/transport D”

java,junit,mule,junit4,junit3
I am getting below exception in Junit test code in Mule. You can find my mule flow and test code here :Getting "muleContext cannot be resolved" error in mule Junit test code Can anyone help me to resove this error please. org.mule.api.registry.ServiceException: Failed to load transport: org/mule/transport D at org.mule.registry.MuleRegistryHelper.createServiceDescriptor(MuleRegistryHelper.java:563)...

In a JUnit test is there a rule to set the subject of the test

java,junit,annotations
I've been writing a lot of JUnit tests lately and see this same boilerplate pattern. public class MathOpTest { private MathOp a; @Before public void setUp(){ a = new MathOp(); } ... } Is there an annotation to set this up for me as I always need to write a...

JUnit error testing and logging

java,junit,slf4j
I am testing in a JUnit test that a custom error is raised in certain cases, with an @Test annotation, and everything goes well. @Test(expected = MyCustomException.class) public void MyTest(){ ... } However, in my code, when I have such an error, I use a logger (slf4j) in such a...

JUnit 4.11 not showing parameter value but index

java,eclipse,ant,junit
We have a project with a number of JUnit testclasses that has been using the Eclipse internal JUnit implementation until recently. In order to run our tests from the ant build script we have changed the build path for our project to use an external junit-4.11.jar and the required hamcrest-core...

How to make Jersey Unit test for Post method

java,rest,junit,jersey,jax-rs
Questions How do create a Jersey Unit Test for a POST? How do I add post parameters? What I tried For a GET it is easy (https://jersey.java.net/documentation/latest/test-framework.html): @Test public void test() { final String hello = target("hello").request().get(String.class); assertEquals("Hello World!", hello); } For a post it is more diffuse. I managed...

java linked list works except in one instance

java,unicode,junit
I am writing a Linked List in Java that is essentially a mixture of Java's String and StringBuilder classes. I have to test it with JUnit and all of the tests pass, except for the last two, where it passes in a string consisting of every character. In this case...

Why does my Junit-AssertionError-Test fail?

java,junit
I run the following test in my Eclipse (with arguments -ea): public class ColorHelperTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testGetColorByString() { thrown.expect(AssertionError.class); assert 1 == 2; } } The output is: java.lang.AssertionError at de.*.*.*.mytests.ColorHelperTest.testGetColorByString(ColorHelperTest.java:28) 28 is the line assert 1==2 Why does this test fail?...

Junit parameterized testing ,a different thought

java,selenium,junit
Here, I have a custom independent component which accept input as a jar file and identify the junit test classes from it and execute them using the code given below. Result result = JUnitCore.runClasses(cls);//cls is Class<?>instance. Next thing I required is a provision to inject parameters (Assuming that input jar...

Some of my tests show prepended with junit.framework

java,unit-testing,jenkins,junit,junit4
I have a set of junit tests that run automatically on my build server (Jenkins). I run more than 500 tests. Most of them, in the test results view, show up with the correct package value Example : results for com.test.app.RollingArchiveTest But I have 8 tests that have junit.framework prepended...

Writing unit test with spring

java,spring,junit
I'm new in unit-testing and trying to intanciate ApplicationContext in a unit-test as follows: ApplicationContext context; @Before public void init(){ context = new ClassPathXmlApplicationContext("classpath://webapp/WEB-INF/applicationContext-sheduler.xml"); } But when I try to do so I get the exception: 2015-05-29 10:20:13,494 ERROR Unable to create file ${sys:catalina.home}/logs/partner-sheduler.log java.io.IOException: The filename, directory name, or...

How to write JUnit tests with progressive state

java,testing,junit
I am new to JUnit and looking for advice. To start myself off I picked a simple helper object, that is used to manage a Table of Strings. The tests have a progression that argues against the granularity encouraged in the guides I've read. Trying to keep the granularity fine...

How to check JSON in response body with mockMvc

java,spring,junit,mocking,spring-test-mvc
This is my method inside my controller which is annotated by @Controller @RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8") @ResponseBody public JSONObject getServerAlertFilters(@PathVariable String serverName) { JSONObject json = new JSONObject(); List<FilterVO> filteredAlerts = alertFilterService.getAlertFilters(serverName, ""); JSONArray jsonArray = new JSONArray(); jsonArray.addAll(filteredAlerts); json.put(SelfServiceConstants.DATA, jsonArray); return json; } I am expecting...

Detect Eclipse version from JUnit test running in Eclipse

java,eclipse,junit
I'm running a series of system tests developed with Java and JUnit within Eclipse, using the Eclipse console as output. I'm planning to implementing better console output for some tests using some console characters, which are not supported before Eclipse Mars (https://bugs.eclipse.org/bugs/show_bug.cgi?id=76936). To ensure compatibility with colleagues running an older...

Creating a JUnit for an array with a number less than 20 in the array, trying to create the assumed array, to then test

java,if-statement,for-loop,junit
Assignment: Write a JUnit test assuming you have an array of int values and you only want the JUnit test to fail if any of the values are less than 20. I know it only asks for the JUnit assuming the other methods are already created. But I want to...

don't let test stop on failure

junit,junit4
I'm looking for the best practice for following (simplified) scenario: @Test public void someTest() { for(String someText : someTexts) { Assert.true(checkForValidity(someText)); } This test iterates through x-thousands of texts and in this case I don't want it to be stopped for each failure. I want the errors to be buffered...

mocking UrlEncoder in a static method

java,junit,mockito,powermock
I'm having trouble mocking UrlEncode.encode method which is inside a static method. MyEncodeClass.java has this method public static myEncode(String s) { UrlEncoder.encode(s, "utf-8"); } I want to force throw an exception when UrlEncode.encode method is called. @Test(expect = UnsupportedEncodingException.class) public void myTest() { PowerMockito.mockStatic(URLEncoder.class); when(URLEncoder.encode("aa", "utf-8")).thenThrow(UnsupportedEncodingException.class); MyEncodeClass.myEncode("aa"); } but I...

WebDriver Selenium browse file Java

java,eclipse,junit,webdriver
Can't browse file using webdriver. driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); driver.findElement(By.id("1434461513889_57_7_input.file")).sendKeys("C:\\PDF_V1_COL88810_6L_Frangipani_TL_Fr_P1211089.pdf"); Have this error: NoSuchElementException: Unnable to locate element: {"method":"id","selector":"BatchUploadPlugin_57_fileupload"} HTML code...

Spring MVC with Mybatis crud : Error fail to load ApplicationContext when testing with Junit

spring,spring-mvc,junit,mybatis,spring-mybatis
I got error when I try to use mybatis crud with spring mvc 4. I use spring mvc project in eclipse/spring tool.I create spring mvc project directly not from maven project Directories mybatisConfig.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true"/> <setting...

ClassNotFoundException when running a junit test in eclipse

java,eclipse,maven,junit,classnotfoundexception
I am really desperate why this exception can even occurs ? I am running test in class MyTestIT. And what class is not found ? Class which I run... I tried to clean and build it again in eclipse but with no success Class not found it.mytest.MyTestIT java.lang.ClassNotFoundException: it.mytest.MyTestIT at...

Junit VerificationModeFactory.times() vs mockito.times()

junit,mocking,verify
What is the difference between VerificationModeFactory.times() and mockito.times()?

Mocking/Testing HTTP Get Request

java,unit-testing,http,junit,mockito
I'm trying to write unit tests for my program and use mock data. I'm a little confused on how to intercept an HTTP Get request to a URL. My program calls a URL to our API and it is returned a simple XML file. I would like the test to...

Why aren't BeforeTransaction and AfterTransaction methods firing?

java,spring,junit,spring-jdbc
I have some unit tests that use JUnit and Spring to test a simple DAO. My understanding is that when I mark a class as @Transactional, the @BeforeTransaction and @AfterTransaction methods should run before and after my @Test methods. However, these methods are not being fired at all. I don't...

JUnit Tests: Why is Maven (Surefire) so much slower than running on Eclipse?

java,maven,unit-testing,junit,spring-test
I'm working on a fairly big application, with ~260k LOC and roughly 1800 unit tests on the suite. A little background: Multi-modular Maven project All tests run on a separate module and JaCoCo is used to check coverage. Tests are put together in some suites and then the suites are...

Selenium test execution via jenkins on linux box

linux,selenium,jenkins,junit,selenium-webdriver
How to run selenium webdriver scripts via jenkins on linux machine and publish the test results in Jenkins? I am using Jenkins as my Continuous integration tool. Jenkins is running in linux machine. I need to run the Selenium test suite during build process in jenkins and publish the results...

Easymock createMock vs @Mock

unit-testing,junit,easymock
I'm using Easymock with junit for writing my unit tests. I have seen different tests following different methods to create mock objects. Is there any difference between Easymock.createMock() and @Mock annotation ? Obj obj = EasyMock.createMock(Obj.class); and @Mock private Obj obj; Is there any difference between the two ?...

Selenium Simple Chrome WebDriver: java compilation and execution problems

java,maven,selenium,junit
I'm new to Selenium and I have little knowledge of the java compilation and run process, because I always compiled and executed with the help of the IDE. My problem I'm trying to run a simple test with selenium (for learning purposes) to request "www.google.com" and assert that the title...

Easymock expectLastCall

unit-testing,junit,easymock
I am using Easymock with junit for writing my unit tests. I have a doubt in this regard and I could not find a very lucid explanation regarding it. How do you test void methods ? Since they do not return anything, so something like : Easymock.expect(myMockObject.func(easymock.isa(String.class))).andReturn("NOTHING TO RETURN HERE");...

Multi user file property Selenium

java,selenium,junit,webdriver,automated-tests
I made autotest on Selenium. This test I will start on JMeter for load testing for 10, 20, 50+ users. What I should do. I create a property file (configuration file) and put there URL, Login, Password. So I made a cycle and put there this code where I'll start...

Java ArrayIndexOutOfBoundsException: 14 when using getMatrix()

java,arrays,matrix,junit
I have the constructor Map() with the attributes sector and Matrix that creates and array of 23x14 and a numerical matrix of 23x14, then i have the constructor MapFermi() that sets an specific numerical matrix and then names each sector according to the numerical value of each matrix cell, when...

Compile with ant classpath issue with JUnit

java,ant,junit,jar,compilation
I am having a compile issue with ant, junit.jar cannot be found here is my build file: <path id="lib"> <fileset dir="library"> <include name="*.jar" /> </fileset> </path> <target name="test"> <mkdir dir="tmp/reports" /> <mkdir dir="tmp/build" /> <javac srcdir="test" destdir="tmp/build" includeantruntime="false"> <classpath refid="lib" /> </javac> <echo message="Build done" /> <junit fork="yes" haltonfailure="yes"> <batchtest...

Jersey JUnit Test: @WebListener ServletContextListener not invoked

java,rest,junit,jersey,jax-rs
I created this test in Jersey (from the docs), which works fine, with one problem: the @WebListener ServletContextListener is not being invoked. The Resource classes that I need to test rely on an attribute set on the ServletContext by the ServletContextListener. Can I make sure it is invoked, or can...

JUnit report to show test functionality, not coverage

java,unit-testing,junit,test-coverage,mutation-testing
One of the problems of a team lead is that people on the team (sometimes even including myself) often create JUnit tests without any testing functionality. It's easily done since the developers use their JUnit test as a harness to launch the part of the application they are coding, and...

Identify test classes dynamically

java,reflection,junit,testng
I required a solution to identify test classes from a jar file and execute them .That is my web application accept a jar file as input and identify test classes inside the jar and execute them and show the result. Currently I am facing class not found exception whenever I...

What is the proper way to setup integration tests in grails 2.5 using junit?

grails,junit,dependency-injection,integration-testing
With grails 2.2 the following code (which is an integration test for a GORM class) was working fine: public class DbDeploymentIntegrationTests extends GroovyTestCase { DeploymentStorageImpl deploymentStorage DeploymentService deploymentService @Override protected void setUp() { super.setUp() deploymentStorage = deploymentService.deploymentService.deploymentStorage } ... } When I updated to grails 2.5, this is now failing:...

Junit using groovy expected exception

java,unit-testing,groovy,junit
I have Spring boot application. I use Junit+Mockito to unit test it. All the test cases were written using Java. I recently made a decision to write test cases using Groovy though the application code will remain in Java. I encountered a weird scenario while testing expected exceptions. Scenario 1:...

Issues in writing test case for a private method

junit,mockito,powermock,easymock,powermockito
I am trying to write a test case for params method in the below class. Problems while writing a JUnit test case: The problem is that the method is private and inside the method it calls for super class methods. I tried using EasyMock where I will be able to...

Java jUnit Birt ClassNotFoundException: org.eclipse.osgi.util.NLS

java,junit,birt
I got the following ClassNotFoundException-Exception, when I tried to create a .pdf-file with Birt: I used jUnit to test my code. In Virgo everything works, but not with jUnit. java.lang.NoClassDefFoundError: org/eclipse/osgi/util/NLS at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:455) at...

JUnit TemporaryFolder does not create the folder

java,junit
In the following code I get the exception java.lang.IllegalStateException: the temporary folder has not yet been created at the getRoot() call. I found this post according to which this code should work. Also, I noticed that if I add temporaryFolder.create(); before the getRoot() call, the code works fine. public class...

Java Failure on JUnit Case Calling a Method from a Subclass

java,methods,junit,subclass
I have the constructor Alieni from the subclass Alieni of the class Settore that sets the name ALIENI from the enum Nome to a certain Settore (composed by the integers coordinataX and coordinataY). The test I'm trying to make is to verify that after running the method Alieni to a...

How to make JUnit test fall down if constuctor is present?

java,junit,tdd
I am learning JUnit and Test Driven Development practice. I have empty Money interface: public interface Money { } CommonMoney class which implements Money interface: public class CommonMoney implements Money { private CommonMoney() { } public static Money create(String decimalPart, Currency currency) { return new Money() { }; } }...

How to test Exceptions with ActivityTestCase or InstrumentationTestCase

java,android,android-studio,junit,junit4
I'm creating some Junit Tests with Android Studio 1.2.2. This is my TestClass. It extends from ActivityTestCase (or InstrumentationTestCase). public class TypeTest extends ActivityTestCase { TypesMeth typesMeth = new TypesMeth(); public void testTypes() { typesMeth.setValue((short) 1000000); assertEquals(exception, typesMeth.getValue()); } } The parameter must be short. So the range is from...

Roboelectric issues with new gradle and android sdk versions

android,junit,robolectric
I used to be able to use roboelectric with gradle just fine until recently. I keep getting an error Error:(6, 17) error: package org.junit does not exist. I'm not quite sure and have dug into this quite a bit. Below is my project build.gradle: // Top-level build file where you...

testing - How to approach integration tests that create new data

testing,junit,automated-tests,integration-testing
Say I have a test that asserts whether registration of a new user in the system actually succeeds: RegistrationIntegrationTest#testRegister() Now, this creates a new test user in the actual database, since I want this test to run on the actual environment. This means that the test must not be run...

Spring Bean Injection Failing Due To Proxy

java,spring,hibernate,junit,mockito
Spring Version: 3.2.4.RELEASE and 3.2.9.RELEASE Mockito Version: 1.8.5 I've been trying to introduce H2 tests to an old project for integration testing, and I've been running into a few issues. Due to the way transactions were propagating, I needed to mock out an autowired class. I've done this before, but...

jUnit Usage of setUp and tearDown [duplicate]

java,junit
This question already has an answer here: setUp/tearDown (@[email protected]) why we need them in JUnit? 6 answers Being new to jUnit what I have done so far is setting up my dependencies (i.e. creating objects) within the test methods itself. Questions: Eclipse mocks about unused variables, though. Is this...

What is the best way to compare tar archives in junit testing

java,junit,tar,apache-commons-compress
I am attempting to create jUnit tests for some code that generates tar files. During testing I will be creating a variety of tar files and comparing them to "Gold" tar images of the expected output. I have been struggling to create an assertTarEquals(String file1, String file2) function, and was...

How to test running threads if they are terminating properly when they all done using JUnit

java,multithreading,junit
I've a server class which listens on a particular port number for the requests made by the clients. And for each client it opens a separate Thread of execution. But the problem is that server program gets hands every after few days and I had to restart that program...

Create a JsonProcessingException

java,junit,jackson,mockito
I'm trying to create a JsonProcessingException to be thrown by a mock object. when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error")); However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?...

java.lang.StackOverflowError while running junit test case

java,eclipse,unit-testing,junit
I am writing junit test cases for a java application Here is junit test code public class CultureMachineTestCases extends CultureMachineAssignment { CultureMachineTestCases testObj=new CultureMachineTestCases(); @Before public void init() throws IOException{ testObj.insertDataIntoSet(); testObj.addKeywords("video1"); } [email protected] public void testVideo() throws IOException { result=testObj.search("abcd"); answer=result.toString(); answer1=answer.replaceAll("[^a-z0-9]",""); assertEquals("video1", answer1); } @Before public void initMethod()...

How to test a void method that prints on console in jUnit?

java,junit
I use a factory pattern. I have 3 currencies: dollars, RON and euro. In each of this classes i have the same function, print, with different output: public void print() { System.out.println("I printed dollars!"); } public void print() { System.out.println("I printed euro!");} In my factory class, i have a method...

Why JUnit using CountDownLatch to implement FailOnTimeout

java,junit,concurrency
I just started to read code of JUnit 4.13 (https://github.com/junit-team/junit), and get a little confused about the implementation of org.junit.internal.runners.statements.FailOnTimeout: @Override public void evaluate() throws Throwable { CallableStatement callable = new CallableStatement(); FutureTask<Throwable> task = new FutureTask<Throwable>(callable); ThreadGroup threadGroup = new ThreadGroup("FailOnTimeoutGroup"); Thread thread = new Thread(threadGroup, task, "Time-limited test");...

Getting “muleContext cannot be resolved” error in mule Junit test code

java,junit,mule,junit4,junit3
I am getting error "Unresolved compilation problem: muleContext cannot be resolved" at the line "MuleClient client = muleContext.getClient();" in JUnit test code in Mule. As per my understanding this code is correct. Since i am new to JUnit, i am not getting why this error is coming. Can anyone help...

How test classes get reference of source classes in junit test?

java,junit
Junit test classes reside in totally different target folders, but while running test cases how is it possible for test class to get reference to the source classes?

Unit Tests - where to place initialization code?

java,unit-testing,junit
I like to have unit tests which are small and just have the call to the function under test and Asserts. But I am confused about where to place the initialization code? There are a lot of variables like request/response objects and others which are used by the unit tests....

How to do junit testing for multiple functions together

java,eclipse,unit-testing,junit
I am writing Junit test cases for one java application. If I run the test functions individually its running fine. When I try to run them together its not running properly Here is JUnit code public class CultureMachineTestCases{ CultureMachineAssignment testObj=new CultureMachineAssignment (); HashSet<String> result =new HashSet<String>(); String answer,answer1; int flagVal;...

Failed to load properties from junit spring

spring,maven,junit,filenotfoundexception,spring-test
I have got a project which works perfectly fine when run via java -jar command but if I run it via junit it fails not able to load property files which are loaded using spring context.Below is the directory structure /src /main /java /resources /config /export export.properties context.xml startJob.bat test...

Total unit test execution time is gone

java,eclipse,unit-testing,junit
I have implemented automated system tests based on JUnit 4. It was always good to know how long a total test run took. The number of seconds was easy to get from the JUnit results window. I have recently upgraded from Eclipse Luna SR 1 to Eclipse Luna SR 2...

Custom FEST Assertions : Displaying readable message with

java,junit,testng,assertions,fest
I have created a custom FEST Condition to verify that my actual string either matches or is equal to an expected String public class StringMatchesOrIsEqualTo extends Condition<String>{ private String expectedStringOrExpression; public StringMatchesOrIsEqualTo(final String expectedStringorExpression){ this.expectedStringOrExpression = expectedStringorExpression; } @Override public boolean matches(String value) { return value.matches(expectedStringOrExpression) || value.equals(expectedStringOrExpression); } }...

JUnit Hamcrest assertion

java,junit,junit4,hamcrest
Is there a Hamcrest Matcher that cleanly lets me assert that the result of a method, that returns a Collection of objects, has at least one object that contains a property with certain value? For example: class Person { private String name; } The method under test returns a collection...

InvocationTargetException in Easy mock of JUnit

java,unit-testing,junit,easymock
I am facing an issue while running JUnit using EasyMock. Please find below the source files - UserTest.java (JUnit file) and UserFinder.java (Application file to be unit tested). UserTest.java Class UserTest { ... @Test public void testFindUserFunction() throws Exception { DAO daoMock = EasyMock.createMock(DAO.class); User user = new User("john", "stephen",...

Multiple Spring datasources for JUnit test

java,spring,junit
I have such simple class for JUnit test: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/mysql-datasource-context.xml"}) public class EmployeeDAOTest { @Autowired EmployeeDao employeeDao; @Test public void findAllTest() { assertTrue(employeeDao.findByName("noname").size() == 0); } } The content of the mysql-datasource-context.xml looks like this: <context:component-scan base-package="my.packages.*"/> <bean id="dataSource"...

Spring Junit with session object - not visible in Controller

java,spring,session,junit,spring-junit
Simple Test class have the following: @Autowired private WebApplicationContext wac; @Autowired MockHttpSession session; private MockMvc mockMvc; @Before public void before() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void testSetSomeType() throws Exception { this.session.putValue("PREV_PAGE_VAL", "FOO"); System.out.println(this.session.getAttribute("PREV_PAGE_VAL")); //FOO is there, so far so good, but in the controller, its null RequestBuilder requestBuilder...

Java: LinkedList findnode() method and isEmpty() method

java,junit
I have a LinkedList class that implements iterable interface, in the LinkedList class i have an inner node class. I have another TestLinkedList class that runs JUnit 4. The test class will check all of my functions in the linkedlist class. Here is my LinkedListClass: public class LinkedList<T> implements Iterable<T>...

How to run junit from command line with vm arguments?

java,junit
Is there any way to run junit test cases with program arguments, VM arguments and working directory? I've tried with org.junit.runner.JUnitCore, but I can't find the way to pass these parameters....

How can performed method setUp only once in tests

java,testing,junit,integration-testing
I have test: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestRepositoryConfig.class}) @Transactional public class ServiceTest { @Autowired private UserRepository userRepository; @Autowired private Service service; static { initTestUser(); } public void setUp() { userRepository.seve(testUser); } public void test1() { ... } public void test2() { ... } I need first start method setUp, saving testUser,...