FAQ Database Discussion Community


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...

Something like theories @TestedOn but usable with Strings? or separate parameterized classes?

java,selenium,junit,junit4
I have a couple different arrays of strings, such as private static final String[] allowed = {"-", "_", "@", ".", "`", "[", "]", "'", "#", "?", "&", "!", "{", "}"}; private static final String[] disallowed = {" ", "/", "*", "~", "|","\\", "<", ">", "\"", "=", "%", "$", "^"}; and...

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...

Jenkins and Running AndroidJUnitRunner Instrumentation Tests

android,jenkins,junit4,build-automation,android-instrumentation
I've got an Android application which I'm trying to set up with Jenkins. I've got it booting up an emulator using the Android Emulator Plugin, and building the project with a gradle script, but I can't get it to run a simple test I wrote utilizing the AndroidJUnitRunner. My output...

Spring Integration Test Loading Annotated Beans

java,spring-boot,integration-testing,junit4
For some reason, my DAO is not loaded when I use @ComponentScan alone. My DAO: @Repository public class MyDAO{ @Autowire private Datasource ds; } My Config class (just overrides datasource bean with an embedded DB): @Configuration public class TestConfig extends AppConfig { @Bean public Datasource getDatasource() throws Exception{...} My Test...

Espresso How to access views without using R.id.viewid as we do in robotium?

android,junit4,robotium,android-testing,android-espresso
I am switching from robotium to espresso, I am writing tests using apk, I dont have access to code. In robotium using solo.getView("view-id") we can access the view but I am not geting how to do it in espresso? espresso witId() method needs R.id.viewid which I dont have access. public...

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)...

“Animators may only be run on Looper threads” during on-device intrumentation testing

java,android,junit,junit4,android-testing
This is my test code: @RunWith(AndroidJUnit4.class) @SmallTest public class WelcomeActivityTests extends BaseTest { ApplicationController applicationController; @Rule public ActivityTestRule<WelcomeActivity> activityTestRule = new ActivityTestRule<>(WelcomeActivity.class); ArgumentCaptor<Callback> argumentCaptor; @Before @Override public void setUp() { applicationController = (ApplicationController) InstrumentationRegistry.getTargetContext().getApplicationContext(); applicationController.setMockMode(true);...

How to test with JUnit through a test case whether a method is executed in another method?

java,junit,junit4
My dice game has a method rollAllDice() which is called when all the dice are rolled by a player. This inturn will call clearAllDiceSelections() method for deselecting the previous selection of all dice. Now I need to write test case for whether the dice were deselected or not ?? public...

check if a List contains elements of another list

java,junit,junit4
Assuming there is a result List R, and an expected List E. List<String> R = ... List<String> E = ... How can I use JUnit's assertTrue(…) to check that R contains at least all elements in E?...

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...

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...

WebDriver can't get dropdown menu element (Java)

java,selenium,webdriver,junit4
I write a script on Java for Selenium WebDriver, and I have a problem with selected from dropdown menu. Here's my locator: new Select(driver.findElement(By.id("FormElement_select_68_input_input"))).selectByVisibleText("Image"); Here's an error: http://prntscr.com/7jul03 Here's HTML code: http://prntscr.com/7jvou6 Need to select "Image" from this menu, but have an error. Before I had the error like this,...

IntelliJ IDEA cannot see Lombok generated code

java,intellij-idea,junit4,lombok,intellij-lombok-plugin
I have a Gradle-based project that uses lombok. I have imported this project into IntelliJ IDEA 14.1 (using the Import External Model import method). I can run the JUnit4 unit tests without problem in Gradle, but IntelliJ seems to have a problem seeing the Lombok generated Getters. This is preventing...

“Address already in use: bind” exception when running Gradle JUnit tests

gradle,spring-boot,junit4,properties-file,springjunit4classrunner
I'm using Spring Boot 1.2.2.RELEASE, JUnit4, and Gradle 2.1 for a RESTful service and am trying to define a properties file which includes and/or overrides values which will be used in JUnit tests only. All tests execute without an issue when invoked as a JUnit test. However, when these same...

How to use jmockit to mock a whole abstract class but exclude one or several methods that should be verified within one JUnit4 test case?

java,junit4,jmockit
I met a following question when use jmockit. I have an abstract class, it also has many concrete (non-abstract) instance methods, now i want to write a JUnit4 test case to verify one non-abstract & instance method of the abstract class but mock up all other methods in the class?...

assertThat vs assertEquals for big String comparison

junit4
Everyone says that we should use the new assertThat from Junit, but, for big Strings comparison it's seems to be some lack of feature. Example: @Test public void testAssertThat() throws Exception { Assert.assertThat("auiehaeiueahuiheauihaeuieahuiaehuieahuaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei", CoreMatchers.equalTo( "auiehaeiueahuiheauihaeuieahuiaehuieaheaiehiaueheauihaeuihaeuiaehuiaehuiaehuiaehaeuihaei" ) ); } @Test public void testAssertEquals() throws Exception { Assert.assertEquals(...

hibernate rollback not working in service layer

hibernate,postgresql,transactions,junit4,spring-4
i have issue in rollback insert/update data in postgresql database, in service layer, where as in DAO layer it is working fine. My DAO junit test Code @ContextConfiguration("classpath:datasource-context-test.xml") @RunWith(SpringJUnit4ClassRunner.class) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) @Transactional public class SellerDAOTest { @Test @Rollback(true) public void testAddSeller() { try { SellerDO sellerDO...

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...

Create Mockito Array of some Object type

java,junit,mockito,junit4
I need to provide some mock object array of this type "TypeA[]". I am trying to do this but getting classcastexception: List mockList = Mockito.anyListOf(TypeA.class); when(someService.create(Mockito.any(TypeB.class), (TypeA[])mockList.toArray())).thenReturn(1); ...

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...

Managing checked exceptions in different JUnit tests

java,unit-testing,junit,junit4,checked-exceptions
I am writing a Java Unit test for one of my method. The method declaration is like this: public int convertToInteger() throws InvalidRomanNumberException { int result=0; BaseRomanNumeral num1, num2; int i=0; if(!validOperation()) throw new InvalidRomanNumberException(); } Now I am trying to write two unit tests. One is to test if...

Error creating bean with name defaultServletHandlerMapping

java,spring,junit4
I converted all my XML Spring configuration to Java code ones, but i am not getting able to run all my test (which they worked before) because i have an ugly exception: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method...

Spring Data neo4j JUnit4 setup

intellij-idea,gradle,neo4j,junit4,spring-data-neo4j-4
I confess I am a total newbie at the Java way of doing things and I am totally lost trying to get a simple unit test running. I am building a data access library and want to unit test it. I am using Spring Data Neo4j 4.0.0.BUILD-SNAPSHOT because I need...

unit test apache http client proxy 407

apache,junit4,apache-httpclient-4.x,http-proxy
I am trying to build a Junit/Integration test which needs to contact an external server. However, I cannot get past the proxy. I get a 407 blank authentication page error. The Test setup I use @Before public void onSetUp() throws Exception { System.setProperty("http.proxyHost", "webproxy-nl.test.com"); System.setProperty("http.proxyPort", "8080"); System.setProperty("https.proxyHost", "webproxy-nl.test.com"); System.setProperty("https.proxyPort", "8080");...

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...

JUnit - parameterized test - multiple constructor calls

java,junit,junit4
I have a list of text files. I can't load them all together, so I constructed a parameterized test, where only some of the files get tested together (test1: file1...file5, test2: file6...file10, ...). The files are loaded in the constructor of the class. The range of files loaded depends on...

Java: Unit Testing, JUnit, Errors

java,eclipse,junit,junit4
This is a small Java application that is designed to calculate a departments total monthly expenses by adding the amounts paid to all the employees in that department. The departments employees are arranged in a hierarchy, which this app seeks to take into account with how it arranges objects. I'm...

Android Espresso how to write tests using apk?

android,junit4,robotium,android-testing,android-espresso
I am a robotium user now switching to Espresso can anyone tell me how to write tests using apk in espresso, as we do in robotium without having acccess to the code but using app apk. And how to access views without R.id.viewid in espresso? as we do in robotium...

SpringMVC Unit testing - Service method is not called

spring,spring-security,mockito,junit4
When I run unit test on the controller by mocking the service bean, it looks like the service method is not called at all. Is this expected behvaior or am I missing something? SearchController.java @Controller public class SearchController { @Autowired SearchService searchService; @RequestMapping(value="/search", method=RequestMethod.GET) public String showSearchPage(Model model){ model.addAttribute("list", searchService.findAll());...

Espresso how to click on a ImageView placed in listview's first item?

android,junit4,android-testing,android-espresso,ui-testing
I have a custom layout for listview, I want to click on a imageview placed in the list view item, overflow icon of the first item in the list view. I want to click on last imageview with id "rcOverflow" My layout, <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="left" android:paddingBottom="10dp" android:paddingTop="5dp"> <ImageView...

No bean named 'transactionManager' is defined - Rename transactionManager

java,junit4,activiti,spring-4
Im running a unit test under jUnit4 + spring4 and the thing is: my transactionManager is not called "transactionManager", it is called "transactionManagerActiviti". If I change the name everything is fine. I tried with this and this very similar question but I can't find the solution to this simple rename...

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...

Mockito Expect an Exception

exception-handling,mockito,junit4,expect,mockmvc
I'm trying to test the method below with Mockito and Junit: @Transactional @RequestMapping(method=RequestMethod.PUT,value ="/updateEmployer/{empId}") public @ResponseBody Object updateEmployer(@PathVariable Integer empId,) throws Exception { Employee e = EmployeeRepository.findOne(empId); for (Department de : e.getDepartement()){ de.setDepartmentName(e.getName + "_" + de.getName()); } EmployeeRepository..saveAndFlush(e); return null; } This is the method Test: @Test // throw...

AndroidJUnit4.class + org.junit.Assume.assumeTrue = AssumptionViolatedException

java,android,junit,junit4,android-testing
I've managed to get my Android project transitioned over to JUnit4, and of course the main reason I wanted to do it isn't working. Would love any help if anyone's got ideas here. The problem I'm trying to solve is that I want to automatically skip certain tests if the...

Espresso how to wait for some time(1 hour)?

android,junit4,android-testing,android-espresso
In my test case I have to record for 1 hour, in robotium solo.sleep(600000) had done my work, but In espresso I am confused with IdlingResource concept. I have to start recording and wait for some time(depending on the type of test) 15mins, 60mins etc. Equivalent code in robotium solo.clickOnView(solo.getView("start_record"));...

Login page Junit test with mockito

java,mockito,junit4
I guess this is simple problem, but I am unable to get my head around it. this is the class for which I need to write test case @Controller @SessionAttributes public class LoginController { @RequestMapping(value = "/Login", method = RequestMethod.GET) public ModelAndView displayLogin(@RequestParam(value = "error", required = false) String error,...

how to mock context datasource for jdbc

java,jdbc,mocking,junit4
I have this code to connect with a Database, which is Defined by a Strutsapplication. public void initConnection() { if (this.con == null) { try { Context ctx = new InitialContext(); Context envContext = (Context)ctx.lookup("java:comp/env"); this.ds = ((DataSource)envContext.lookup("jdbc/FooBar")); if (this.ds != null) { this.con = this.ds.getConnection(); if (this.con != null)...

unable to mock generic object creation

java,mockito,junit4,generic-collections
I want to mock dao creation for following method. private ReturnType createTenant(){ TenantDto tenantDto = new TenantDto(); TenantGroupDto tenantUserGroupDto = new TenantGroupDto(DEFAULT_USER_GROUP_NAME,Type.HUMAN,DEFAULT_USER_GROUP_DESCR, true); TenantGroupDto tenantDeviceGroupDto = new TenantGroupDto(DEFAULT_DEVICE_GROUP_NAME,Type.DEVICE,DEFAULT_DEVICE_GROUP_DESCR, true); Set<TenantGroupDto> tenantGroups = new HashSet<TenantGroupDto>(); tenantGroups.add(tenantUserGroupDto); tenantGroups.add(tenantDeviceGroupDto);...

Null pointer exception thrown when creating a Double to test null check

java,unit-testing,junit,junit4
This may be a stupid question, but I have a method that will convert Doubles or BigDecimals to a formatted String: //There is also a method that accepts BigDecimals public String convertToCurrencyString(Double aAmount) { if(aAmount == null){ return "$0.00"; } NumberFormat numFormat = DecimalFormat.getCurrencyInstance(Locale.US); numFormat.setMinimumFractionDigits(2); String amount = numFormat.format(aAmount); return...

Autowire jdbcTemplate in ObjectMother for a junit 4 integration test

java,integration-testing,junit4,autowired,jdbctemplate
I was wondering if I can somehow autowire jdbcTemplate in the ObjectMother for a junit 4 integration Test. The purpose of the test is to test that if you attach a document to an employee, you cannot attach afterwards a document with the same name. For that I made an...

Field mContext is null in my AndroidTestCase but only when I run it with JUnit4

android,junit4,android-testing
Is this an issue or did I forget to implement something particular? When I don't run it with JUnit 4 it works fine....

Resources$NotFoundException when calling Robolectric.buildActivity()

java,android,unit-testing,junit4,robolectric
I am using Robolectric 3.0 RC3 for unit testing in Android Studio. And I am getting a ResourceNotFoundException every time I run the test. Please help me resolve the issue. build.gradle dependencies { testCompile 'junit:junit:4.12' compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.0.0' testCompile 'org.mockito:mockito-core:1.9.5' testCompile 'org.robolectric:robolectric:3.0-rc3' compile 'com.ibm.icu:icu4j:53.1' } Test...

JUnit test method comparing DateTimes fails only when run from suites

java,junit,java-7,junit4
A single JUnit test being run under JUnit 4.11 fail the majority of the time while being run via either to module test suite (40 runs: 2 failures, 38 passes), or the class test suite (40 runs: 6 failures, 34 passes), but running the test method by itself did not...

disable @EnableScheduling on spring tests

spring,unit-testing,junit,junit4,springjunit4classrunner
When I run my unit tests and it invokes my scheduled tasks - I dont want it to do this. It is because I have @EnableScheduling on my main app configuration. How can I disable this on my unit tests? I have come across this question/answer which suggests setting up...