Use of #Parameters annotation in junit 4.11-SNAPSHOT - java

I want to make use of the new functionality in the latest build of junit in order to name my parameterized tests
I have the following two tests written in java & scala, but the scala test generates a compiler error:
error: unknown annotation argument name: name #Parameters(name =
"{0}") def data: util.Collection[Array[AnyRef]] =
util.Arrays.asList(Array("x"), Array("y"), Array("z"))
What is the difference in implementation causing this error?
java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.fail;
#RunWith(Parameterized.class)
public class ParameterizedTest {
#Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[]{"x"}, new Object[]{"y"}, new Object[]{"z"});
}
#Test
public void foo() {
fail("bar");
}
}
scala
import java.util
import org.junit.Assert._
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized._
#RunWith(classOf[Parameterized])
class ParameterizedScalaTest {
#Test def foo() {
fail("bar")
}
}
object ParameterizedScalaTest {
#Parameters(name = "{0}") def data: util.Collection[Array[AnyRef]] = util.Arrays.asList(Array("x"), Array("y"), Array("z"))
}

Because #Parameters is defined as an inner, you seem to need to give the full name.
Try
#Parameters(Parameters.name = "{0}")
At least, that is the only significant difference I can observe in the definitions of #Parameters and #Test, and this works:
#Test(timeout = 10)

It turns out the issue here is due to junit-dep.jar being on the classpath through a transient dependency on jMock 2.4.0
Removing that fixed the compiler error, odd that this is an issue for scalac but not javac.

Related

I have a Junit4 test with a RuntimeException "should have no parameters" for a parameterized test

I'm running some code using Junit4 and an external jar of JunitParams.
As far as I could tell, my code was all set right, and imports are all correct...but my method under test keeps throwing runtime exceptions since it seems to ignore the #Parameters annotation hanging out in it.
When it reaches my method under test, it keeps saying "java.lang.Exception: Method ----- should have no parameters"
I'm not sure what the issue is, even though other people have run into issues with mix/matched import statements, etc. I checked mine and that doesn't seem like the case here.
Test Runner class:
package Chapter8.Wrappers.Tests;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args){
Result result = JUnitCore.runClasses(StringProcessorTest.class);
for(Failure failures: result.getFailures()) {
System.out.println(failures.toString());
}
System.out.println(result.wasSuccessful());
}
}
and my test class, StringProcessorTest :
package Chapter8.Wrappers.Tests;
import Chapter8.Wrappers.Challenges.BackwardsString.StringProcessor;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.Collection;
#RunWith(JUnitParamsRunner.class)
public class StringProcessorTest {
private StringProcessor processor;
private final String expectedResult;
private final String inputString;
public StringProcessorTest(String inputString, String expectedResult){
super();
this.inputString = inputString;
this.expectedResult = expectedResult;
}
#Before
public void initialize(){
processor = new StringProcessor();
}
#Parameters
public static Collection stringValues(){
return Arrays.asList(new Object[][] { {"HELLO","OLLEH"},
{"TESTING", "GNITSET"} });
}
#Test
public void objectConstructor_InitializeStringBuilderInside_EqualsPassedString(String inputString, String expectedResult){
Object input;
input = inputString;
processor = new StringProcessor(input);
Assert.assertEquals(expectedResult, processor.printReverseString());
}
}
Console output:
Chapter8.Wrappers.Tests.StringProcessorTest: java.lang.Exception: Method objectConstructor_InitializeStringBuilderInside_EqualsPassedString should have no parameters
false
Process finished with exit code 0
I found something that ended up working out- I changed the inside of the #RunWith annotation to
Parameterized.class
It turned out I was trying to pass parameters into the method under the #Test annotation, and not just the constructor of my StringProcessorTest class; I removed them from the method under test. It was already warning me about that but I didn't understand why earlier.
When I re-ran it, it completed without issues and ran both times.
I think you have two choices to resolve your issue:
Remove the #Parameters annotation from stringValues() method and add it to your test method like this:
private List stringValues(){
return Arrays.asList(new Object[][] { {"HELLO","OLLEH"}, {"TESTING", "GNITSET"} });
}
#Test
#Parameters(method = "stringValues")
public void objectConstructor_InitializeStringBuilderInside_EqualsPassedString(String inputString, String expectedResult) {
processor = new StringProcessor(inputString);
Assert.assertEquals(expectedResult, processor.printReverseString());
}
OR
Remove stringValues() method and put the #Parameters annotation directly on your test method:
#Test
#Parameters({ "HELLO, OLLEH", "TESTING, GNITSET" })
public void objectConstructor_InitializeStringBuilderInside_EqualsPassedString(String inputString, String expectedResult) {
processor = new StringProcessor(inputString);
Assert.assertEquals(expectedResult, processor.printReverseString());
}

Lenient string matching with Mockito Mock

I have a test to verify the return of a null object if a string property of that object does not match a pre-determined value. My code is
import guru.springframework.sfgpetclinic.model.Speciality;
import guru.springframework.sfgpetclinic.repositories.SpecialtyRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.BDDMockito.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
#ExtendWith(MockitoExtension.class)
class SpecialtySDJpaServiceTest {
#Mock
SpecialtyRepository specialtyRepository;
#InjectMocks
SpecialtySDJpaService service;
#Test
void testSaveLambdaNoMatch() {
// Given
final String MATCH_ME = "MATCH_ME";
Speciality speciality = new Speciality();
speciality.setDescription("Not a match");
Speciality savedSpeciality = new Speciality();
savedSpeciality.setId(1L);
// Need mock to only return on match MATCH_ME string
given(specialtyRepository.save(argThat(argument -> argument.getDescription().equals(MATCH_ME)))).willReturn(savedSpeciality);
// When
Speciality returnedSpeciality = service.save(speciality);
// Then
assertNull(returnedSpeciality);
}
// Other tests...
}
This test fails with the message
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'save' method:
specialtyRepository.save(
guru.springframework.sfgpetclinic.model.Speciality#19ae6bb
I believe the issue is that argThat() uses an exact matching scheme. I want to set the mock matching to lenient via
#Mock(lenient = true)
SpecialtyRepository specialtyRepository
But Intellij does not recognize the lenient parameter. I'm using JUnit 5 and Mockito 2.23.0
#Mock(lenient = true) was introduced in Mockito version 2.23.3.
You either have to upgrade or use the other way to write this:
lenient().when(specialtyRepository.save(argThat(argument -> argument.getDescription().equals(MATCH_ME)))).willReturn(savedSpeciality);

The method multiply(int, int) is undefined for the type Junit

I have typed a simple program in eclipse for Junit testing, but it shows an error: "The method multiply(int, int) is undefined for the type Junit".
package test;
import static org.junit.Assert.*;
import org.junit.Test;
class MultiplyTest {
#Test
void testMultiply() {
Junit test=new Junit();
int result = test.multiply(3,4);
assertEquals(12,result);
}
}
Have you written import for Junit class in MultiplyTest class? and What is the package name of Junit class? and i think #Test annotated method should be public.

PowerMockito mocking static method fails when calling method on parameter

I'm trying to test a class which uses a calculator class with a number of static methods. I've successfully mocked another class in a similar way, but this one is proving more stubborn.
It seems that if the mocked method contains a method call on one of the passed in arguments the static method is not mocked (and the test breaks). Removing the internal call is clearly not an option. Is there something obvious I'm missing here?
Here's a condensed version which behaves the same way...
public class SmallCalculator {
public static int getLength(String string){
int length = 0;
//length = string.length(); // Uncomment this line and the mocking no longer works...
return length;
}
}
And here's the test...
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.solveit.aps.transport.model.impl.SmallCalculator;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ SmallCalculator.class})
public class SmallTester {
#Test
public void smallTest(){
PowerMockito.spy(SmallCalculator.class);
given(SmallCalculator.getLength(any(String.class))).willReturn(5);
assertEquals(5, SmallCalculator.getLength(""));
}
}
It seems there's some confusion about the question, so I've contrived a more 'realistic' example. This one adds a level of indirection, so that it doesn't appear that I'm testing the mocked method directly. The SmallCalculator class is unchanged:
public class BigCalculator {
public int getLength(){
int length = SmallCalculator.getLength("random string");
// ... other logic
return length;
}
public static void main(String... args){
new BigCalculator();
}
}
And here's the new test class...
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.solveit.aps.transport.model.impl.BigCalculator;
import com.solveit.aps.transport.model.impl.SmallCalculator;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ SmallCalculator.class})
public class BigTester {
#Test
public void bigTest(){
PowerMockito.spy(SmallCalculator.class);
given(SmallCalculator.getLength(any(String.class))).willReturn(5);
BigCalculator bigCalculator = new BigCalculator();
assertEquals(5, bigCalculator.getLength());
}
}
I've found the answer here https://blog.codecentric.de/en/2011/11/testing-and-mocking-of-static-methods-in-java/
Here's the final code which works. I've tested this approach in the original code (as well as the contrived example) and it works great. Simples...
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ SmallCalculator.class})
public class BigTester {
#Test
public void bigTest(){
PowerMockito.mockStatic(SmallCalculator.class);
PowerMockito.when(SmallCalculator.getLength(any(String.class))).thenReturn(5);
BigCalculator bigCalculator = new BigCalculator();
assertEquals(5, bigCalculator.getLength());
}
}
First of all, remove that line:
given(SmallCalculator.getLength(any(String.class))).willReturn(5);
Since you are testing the same method. You don't want to mock the method that you're testing.
Secondly, modify your annotation to:
#PrepareForTest({ SmallCalculator.class, String.class})
Lastly, add the mock for the length(); like this:
given(String.length()).willReturn(5);
I think it will do ;)
Use anyString() instead of any(String.class).
When using any(String.class) the passed argument is null, as Mockito will return the default value for the reference type, which is null. As a result you get an exception.
When using the anyString(), the passed argument will be empty string.
Note, this explains why you get an exception, however you need to review the way you test your method, as explained in other comments and answers.
If you do not want that actual method being invoked. Instead of
when(myMethodcall()).thenReturn(myResult);
use
doReturn(myResult).when(myMethodCall());
It is mocking magic and it is difficult to explain why it is actually works.
Other thing you forgot is mockStatic(SmallCalculator.class)
And you do not need PowerMockito.spy(SmallCalculator.class);

The method assertEquals(String, String) is undefined for the type TestJunit

I am new to JUnit.
I just started working on JUnit and i am getting following error.
The method assertEquals(String, String) is undefined for the type TestJunit
and my Javacode:
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class TestJunit {
String message = "Hello World";
MessageUtil messageutil = new MessageUtil(message);
public void testPrintMessage()
{
assertEquals(message,messageutil.printMessage());
}
}
please help me resolve this issue.
You imported
import static org.junit.Assert.assertArrayEquals;
but not
import static org.junit.Assert.assertEquals;
You could also import every static member of Assert with
import static org.junit.Assert.*;
Without these, Java thinks you are calling the method assertEquals defined in the class the code is declared in. Such a method does not exist.
if importing doesn't work try saving before you run the code

Categories

Resources