Why must jUnit’s fixtureSetup be static?

JUnit always creates one instance of the test class for each @Test method. This is a fundamental design decision to make it easier to write tests without side-effects. Good tests do not have any order-of-run dependencies (see F.I.R.S.T) and creating fresh instances of the test class and its instance variables for each test is crucial … Read more

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the ‘result’ and verify it’s correct. import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.*; import javax.servlet.http.*; import org.apache.commons.io.FileUtils; import org.junit.Test; public class TestMyServlet extends Mockito{ @Test public void testServlet() throws … Read more

How to intercept SLF4J (with logback) logging via a JUnit test?

The Slf4j API doesn’t provide such a way but Logback provides a simple solution. You can use ListAppender : a whitebox logback appender where log entries are added in a public List field that we could use to make our assertions. Here is a simple example. Foo class : import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class … Read more

Multiple RunWith Statements in jUnit

You cannot do this because according to spec you cannot put the same annotation twice on the same annotated element. So, what is the solution? The solution is to put only one @RunWith() with runner you cannot stand without and replace other one with something else. In your case I guess you will remove MockitoJUnitRunner … Read more

Separation of JUnit classes into special test package?

I prefer putting the test classes into the same package as the project classes they test, but in a different physical directory, like: myproject/src/com/foo/Bar.java myproject/test/com/foo/BarTest.java In a Maven project it would look like this: myproject/src/main/java/com/foo/Bar.java myproject/src/test/java/com/foo/BarTest.java The main point in this is that my test classes can access (and test!) package-scope classes and members. As … Read more

Using PowerMockito.whenNew() is not getting mocked and original method is called

You need to put the class where the constructor is called into the @PrepareForTest annotation instead of the class which is being constructed – see Mock construction of new objects. In your case: ✗ @PrepareForTest(MyQueryClass.class) ✓ @PrepareForTest(A.class) More general: ✗ @PrepareForTest(NewInstanceClass.class) ✓ @PrepareForTest(ClassThatCreatesTheNewInstance.class)

JUnit vs TestNG [closed]

I’ve used both, but I have to agree with Justin Standard that you shouldn’t really consider rewriting your existing tests to any new format. Regardless of the decision, it is pretty trivial to run both. TestNG strives to be much more configurable than JUnit, but in the end they both work equally well. TestNG has … Read more