My intention is to use assertArrayEquals(int[], int[]) JUnit method described in the API for verification of one method in my class.
But Eclipse shows me the error message that it can't recognize such a method. Those two imports are in place:
import java.util.Arrays;
import junit.framework.TestCase;
Did I miss something?
This would work with JUnit 5:
import static org.junit.jupiter.api.Assertions.*;
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
This should work with JUnit 4:
import static org.junit.Assert.*;
import org.junit.Test;
public class JUnitTest {
/** Have JUnit run this test() method. */
#Test
public void test() throws Exception {
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
}
}
This is the same for the old JUnit framework (JUnit 3):
import junit.framework.TestCase;
public class JUnitTest extends TestCase {
public void test() {
assertArrayEquals(new int[]{1,2,3},new int[]{1,2,3});
}
}
Note the difference: no Annotations and the test class is a subclass of TestCase (which implements the static assert methods).
This could be useful if you want to use just assertEquals without depending on your Junit version
assertTrue(Arrays.equals(expected, actual));
Try to add:
import static org.junit.Assert.*;
assertArrayEquals is a static method.
If you are writing JUnit 3.x style tests which extend TestCase, then you don't need to use the Assert qualifier - TestCase extends Assert itself and so these methods are available without the qualifier.
If you use JUnit 4 annotations, avoiding the TestCase base class, then the Assert qualifier is needed, as well as the import org.junit.Assert. You can use a static import to avoid the qualifier in these cases, but these are considered poor style by some.
Related
Looking at the two test classes below I assume the same behavior from them: to have an UnnecessaryStubbingException thrown. However MyTest2 does not. The MockitoExtension class should have strictness set to strict stubs by default. I can't seem to find any documented information about this behavior and I really want to understand it.
I prefer to write my tests as MyTest2 because I like to have final fields wherever possible, though I also really enjoy the strict stubs check done by Mockito.. Please help my understand the difference between the two tests.
package example;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
#ExtendWith(MockitoExtension.class)
class MyTest {
#Mock
List<Integer> integerList;
#Test
void test() {
Mockito.when(integerList.size()).thenReturn(10);
System.out.println("Do something not involving list");
Assertions.assertTrue(true);
}
}
#ExtendWith(MockitoExtension.class)
class MyTest2 {
final List<Integer> integerList;
MyTest2(#Mock List<Integer> integerList) {
this.integerList = integerList;
}
#Test
void test() {
Mockito.when(integerList.size()).thenReturn(10);
System.out.println("Do something not involving list");
Assertions.assertTrue(true);
}
}
I found the reason in the mockito documentation:
Mockito JUnit Runner triggers UnnecessaryStubbingException only when none of the test methods use the stubbings. This means that it is ok to put default stubbing in a 'setup' method or in test class constructor. That default stubbing needs to be used at least once by one of the test methods.
If you do not want the exception to be thrown for the MyTest class, you can use Mockito.lenient or MockitoSettings. But I guess it is not possible to activate the exception for the MyTest2 class.
I have two TestNG classes containing a few #Test annotations, nothing fancy, and test methods just under them. When I select both of my class files in Eclipse, right-click, choose TestNG - Convert to TestNG, I am presented with a refacotoring wizard in Eclipse to create said testng.xml suite. But when I cliked Next, I'm asked to refactor my code and include org.testng.AssertJUnit.
Why JUnit? What does JUnit have to do with this?
Here's a code sample:
package seleniumTestovi.Pages; import org.testng.Assert;
import org.testng.annotations.Test;
public class NewTest {
#Test
public void foo() {
Assert.assertTrue(true);
}
}
And here is the code Eclipse wants me to refactor when i try to create testng.xml suite.
package seleniumTestovi.Pages;
import org.testng.annotations.Test;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class NewTest {
#Test
public void foo() {
AssertJUnit.assertTrue(true);
}
}
I have two separate junit test .java files. it has the following convention below
import org.mockito.Mock;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
#Test (groups = "integration")
public class myOneIntegrationTest {
#BeforeMethod
#SneakyThrows
public void beforeMethod() {...}
#AfterMethod
public void afterMethod() {...}
#Test
#SneakyThrows
public void testOne() {...}
the test file is localized so that it is testing for one object
I need a test for a functionality that requires an object created in beforeMethod in javaOne.java and another object created in beforeMethod of javaTwo.java
i really dont want to copy-paste beforeMethod from each java files. Is it possible to just import it and test it in javaThree.java?
There is a creational pattern which is derived from the factory pattern called Object Mother.
Martin Fowler wrote an Article in 2006 about it with further readings.
In my opinion this is well suited for testing but you really should replace any boiler plate code with one generated through Lombok (e.g. #Builder).
The following snippet is enough to reproduce my problem:
Either I set the thrown attribute public and get the error org.jboss.weld.exceptions.DefinitionException: WELD-000075: Normal scoped managed bean implementation class has a public field
Or I remove the public modifier and get the error org.junit.internal.runners.rules.ValidationError: The #Rule 'thrown' must be public.
I also tried to let the public modifier in place and to add the #Dependent annotation scope on the class, but got error org.jboss.weld.exceptions.DefinitionException: WELD-000046: At most one scope may be specified on [EnhancedAnnotatedTypeImpl] public #Dependent #ApplicationScoped #RunWith
I stripped out all unnecessary code, but this is quite a complex unit test with mock, service injection through CDI and some test methods thar are expected to throw an exception.
import org.jglue.cdiunit.CdiRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
#RunWith(CdiRunner.class)
public class FooBarTest {
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void test() {
}
}
So my problem is that on one hand Weld wants all fields to not be public because it will not be able to proxify the class otherwise, and on the other hand, JUnit want Rule fields to be public because it is using reflection to access them and does not want to use the setAccessible(true) method because of the cases where the security manager is active. How to deal with that paradox?
NB: I also found a hint comments to this answer, stating that
You can also annotate a method with #Rule, so this would avoid the problem
But I could not found any example of junit test with a #Rule annotation on a method, I plan to ask a separate question about this.
I found out how to solve the problem. For future reference, here is a snippet that works, hope this will help other people.
import org.jglue.cdiunit.CdiRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
#RunWith(CdiRunner.class)
public class FooBarTest {
private ExpectedException thrown = ExpectedException.none();
#Rule
public ExpectedException getThrown() {
return thrown;
}
#Test
public void test() {
thrown.expect(ArithmeticException.class);
int i = 1 / 0;
}
}
I'm trying to write a VERY simple test, using powermock and Robolectric. Here's my code:
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.robolectric.RobolectricTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(RobolectricTestRunner.class)
#PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
#PrepareForTest(BadStaticClass.class)
public class SomeActivityTest {
#Test
public void testSomething() {
PowerMockito.mockStatic(BadStaticClass.class);
Mockito.when(BadStaticClass.dontWantThisMethod()).thenReturn(false);
new SomeActivity().usesStatic();
}
}
Basically, i have a class, "SomeActivity", and it has a method that makes a call to BadStaticClass.dontWantThisMethod(). i want that static method to be stubbed out.
why is my code not working?
i kept getting errors like:
you are trying to stub a final method, you naughty developer!
which, i thought the whole point of PowerMock was to not see that.
According to the PowerMock API you have to include #RunWith(PowerMockRunner.class) for certain versions of JUnit, etc. However you also need to be using #RunWith(RobolectricTestRunner.class) and cannot specify more than one #RunWith on a Class.
So what to do?
I suspect you can keep your code above and introduce a JUnit #Rule (see: PowerMockRule docs) and also described in this similar post. Just be sure you check the versions of the Jars you are using so that they match those described in that other SO post. All too often things just won't work unless you get compatible versions, and it's not always obvious what versions are compatible.