intellij junit working directory

if the working directory for junit test is not properly set, the resource file might not be able to be loaded if relative path is used. By default, Intellij uses project path as working directory. However if you have sub-modules which are in the sub directories, the junit test might have problem running locally. To…

JUnit test with Mockito and Spring

Deveop Mockito, Spring and JUnit tests The code source bellow presents a JUnit test using Spring-test and Mockito framework. @RunWith(SpringJUnit4ClassRunner.class) runs the test with Spring custom runner that will load Spring application context. @Autowire associate invoiceService reference to the InvoiceService instance. @Before annotation executes the setup method before the test. MockitoAnnotations.initMocks(this) scans the class annotation,…

use log4j in junit test assertions

I need to confirm that some error/warnings are logged in the code being tested. The logger is usually private static final that we cannot get from the junit. The following pattern would be able to achieve it.  

Proper way to access file resources in junit tests

As I was refactoring some JUnit tests recently I was reminded of an important fact on the proper way to read in a file. In maven any file under /src/test/resources is automatically copied over to /target/test-classes. So for example lets say I need to read in a wsdl in my test. So I place the wsdl in the resources folder: /src/test/resources/test.wsdl. Now at…

jUnit assertThat matchers

Matchers is an external addition to the JUnit framework. Matchers were added by the framework called Hamcrest. JUnit 4.8.2 ships with Hamcrest internally, so you don’t have to download it, and add it yourself. Matchers are used with the org.junit.Assert.assertThat() method, which looks like this: public void assertThat(Object o, Matcher matcher){ … } You can implement your…

Spring Junit Test

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations=”classpath:/applicationContext.xml”) //or something like “file:WebContent/WEB-INF/applicationContext.xml” @TransactionConfiguration(defaultRollback=true, transactionManager=”transactionManager”)//this ensure that spring would rollback the transaction so that the test will not change the database. @Transactional public class YourTest {    @Autowired   private  MenuDao md;      public void someTest() {     } } When there are multiple test cases, make the above class…