I'm having a little problem with a unit-test my professor gave me. Upon compilation, I recieve the following errors:
cannot find symbol import org.junit.Assert.assertArrayEquals;
cannot find symbol import org.junit.Assert.assertEquals;
import org.junit.Assert.assertFalse;
import org.junit.Assert.assertTrue;
I have downloaded JUnit and I can compile a similar file, so why am I having problems with this?
The code is:
import java.util.Comparator;
import org.junit.Assert.assertArrayEquals;
import org.junit.Assert.assertEquals;
import org.junit.Assert.assertFalse;
import org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class SortingTests {
class IntegerComparator implements Comparator<Integer> {
#Override
public int compare(Integer i1, Integer i2) {
return i1.compareTo(i2);
}
}
private Integer i1,i2,i3;
private OrderedArray<Integer> orderedArray;
#Before
public void createOrderedArray(){
i1 = -12;
i2 = 0;
i3 = 4;
orderedArray = new OrderedArray<>(new IntegerComparator());
}
#Test
public void testIsEmpty_zeroEl(){
assertTrue(orderedArray.isEmpty());
}
#Test
public void testIsEmpty_oneEl() throws Exception{
orderedArray.add(i1);
assertFalse(orderedArray.isEmpty());
}
#Test
public void testSize_zeroEl() throws Exception{
assertEquals(0,orderedArray.size());
}
}
What you are looking for is a Static import
The line import org.junit.Assert.assertArrayEquals; is referencing the method assertArrayEquals from the class org.junit.Assert
Importing a static method so that it is callable like assertEquals(0,orderedArray.size()); is done with a static import line. Try out the following:
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
Alternatively you can:
import static org.junit.Assert.*;
, or you could:
import org.junit.Assert;
and reference the methods like
Assert.assertEquals(0,orderedArray.size());
Assuming that you have the JUnit dependency in the classpath, use import static for the assert methods:
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
Or simply use:
import static org.junit.Assert.*;
You should add the keyword static to import it. An example:
import static org.junit.Assert.assertFalse;
If you are using junit version 5 and above then use org.junit.jupiter.api.assertions .
Path has been moved in junit 5
Related
When I am trying to MOC the dependent classes (instance variables), it is not getting mocked for abstract class. But it is working for all other classes. Any idea how to resolve this issue. I know, I could cover this code from child classes. But I want to know whether it is possible to cover via abstract class or not. Also, I want to use Mockito to resolve it.
Currently, I am getting a NULL point exception on the following line because the mamApiDao is null & not getting mocked
OvpStatusResponse ovpStatusResponse = mamApiDao.updateOvpMetadataInMam(null, callbackMessage.getMediaId(), ovpStatus, publishMessage);
Abstract class
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qvc.qq.mamapimodel.model.mamapi.OvpStatus;
import com.qvc.qq.mamapimodel.model.mamapi.response.OvpStatusResponse;
import com.qvc.qq.mammessageprocessor.config.settings.MqMessageSettings;
import com.qvc.qq.mammessageprocessor.dao.MamApiDao;
import com.qvc.qq.mammessageprocessor.manager.ErrorMessageManager;
import com.qvc.qq.mammessageprocessor.model.CdnCallbackMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.server.ResponseStatusException;
public abstract class CallbackManager {
private final MamApiDao mamApiDao;
public CallbackManager( MamApiDao mamApiDao) {
this.mamApiDao = mamApiDao;
}
public void processCallback(CdnCallbackMessage callbackMessage, int retries, OvpStatus ovpStatus, String publishMessage) {
// some code
//mamApiDao is NULL, it is not getting mocked
OvpStatusResponse ovpStatusResponse = mamApiDao.updateOvpMetadataInMam(null, callbackMessage.getMediaId(), ovpStatus, publishMessage);
// some code
}
}
Test Class
import com.qvc.qq.mamapimodel.model.mamapi.OvpStatus;
import com.qvc.qq.mamapimodel.model.mamapi.response.OvpStatusResponse;
import com.qvc.qq.mammessageprocessor.config.settings.MqMessageSettings;
import com.qvc.qq.mammessageprocessor.dao.MamApiDao;
import com.qvc.qq.mammessageprocessor.dao.MqMessagingDao;
import com.qvc.qq.mammessageprocessor.model.CdnCallbackMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.isNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CallbackManagerTest {
#InjectMocks
CallbackManager callbackManager = Mockito.mock(CallbackManager.class, Mockito.CALLS_REAL_METHODS);
#Mock
MamApiDao mamApiDao;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
#Test
public void processCallbackTest() {
when(mamApiDao.updateOvpMetadataInMam(any(), anyString(), any(), anyString())).thenReturn(new OvpStatusResponse());
callbackManager.processCallback(cdnCallbackMessage, 1, OvpStatus.ACTIVE, "published");
verify(mamApiDao, times(1)).updateOvpMetadataInMam(any(), anyString(), any(), anyString());
}
}
Enum Class
public enum OvpStatus {
SUBMITTED("SUBMITTED"),
ACTIVE("ACTIVE"),
INACTIVE("INACTIVE"),
ERROR("ERROR"),
NONE("NONE");
private String value;
private OvpStatus(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
Dao class
import com.qvc.qq.mamapimodel.model.mamapi.OvpStatus;
import com.qvc.qq.mamapimodel.model.mamapi.response.OvpStatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
#Slf4j
#Component
public class MamApiDao {
public OvpStatusResponse updateOvpMetadataInMam(String mamId, String ovpId, OvpStatus status, String publishMessage) {
OvpStatusResponse ovpStatusResponse = new OvpStatusResponse();
ovpStatusResponse.setId(1);
ovpStatusResponse.setStatus("");
return ovpStatusResponse;
}
}
Test Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
can you try like the below one?
public class CallbackManagerTest {
#InjectMocks
CallbackManager callbackManager = Mockito.mock(CallbackManager.class, Mockito.CALLS_REAL_METHODS);
#MockBean
private MamApiDao mamApiDao;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
//do something
This is the class and the corresponding test I have written for it. Can someone please help me understand why System.out.println(a.size()) prints 0 , when it should print 1000?
WorkingwithLists.java
import java.util.ArrayList;
import java.util.List;
public class WorkingwithLists
{
public static void main(String[] args) {
}
public void ListFunctions()
{
List<String > a=new ArrayList<>();
System.out.println(a.size());
}
}
WorkingwithListsTest.java
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;
public class WorkingwithListsTest
{
#Mock
private List<String> a;
private WorkingwithLists workingwithLists;
#BeforeMethod
public void setup()
{
MockitoAnnotations.openMocks(this);
workingwithLists=new WorkingwithLists();
}
#Test
public void testListFunctions() throws Exception
{
when(a.size()).thenReturn(1000);
workingwithLists.ListFunctions();
}
}
I am not sure why you want that, but to achieve that you have to move the "List a" to class level in order to "Mock" and return whatever you want.
I have below example working, Hope this helps :
import java.util.ArrayList;
import java.util.List;
public class WorkingwithLists{
List<String > a=new ArrayList<>();
public static void main(String[] args) {
}
public void ListFunctions(){
System.out.println(a.size());
}
}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
#RunWith(MockitoJUnitRunner.class)
public class WorkingwithListsTest{
#InjectMocks
WorkingwithLists workingwithLists;
#Mock
private List<String> a;
#Before
public void setup(){
Mockito.when(a.size()).thenReturn(1000);
}
#Test
public void testListFunctions() throws Exception{
workingwithLists.ListFunctions();
Assert.assertTrue(true);
}
}
Output :
I have a class which I would like to test with a public method that calls private one. I'd like to assume that private method works correctly. For example, I'd like something like doReturn....when.... I found that there is possible solution using PowerMock, but this solution doesn't work for me.
How It can be done? Did anybody have this problem?
I don't see a problem here. With the following code using the Mockito API, I managed to do just that :
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
And here's the JUnit test :
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 static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
#RunWith(PowerMockRunner.class)
#PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
#Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());
when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
.withArguments(anyString(), anyInt())
.thenReturn(true);
spy.meaningfulPublicApi();
}
}
A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.
Change your private method to protected.
In your test class extend the class
override the previously-private method to return whatever constant you want
This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.
To mock a private method directly, you'll need to use PowerMock as shown in the other answer.
For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.
import java.util.Random;
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
The test class looks as follows:
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 static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;
#RunWith(PowerMockRunner.class)
#PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
private CodeWithPrivateMethod classToTest;
#Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
classToTest = PowerMockito.spy(classToTest);
doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());
classToTest.meaningfulPublicApi();
}
}
i know a way ny which you can call you private function to test in mockito
#Test
public void commandEndHandlerTest() throws Exception
{
Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
retryClientDetail_privateMethod.setAccessible(true);
retryClientDetail_privateMethod.invoke(yourclass.class, null);
}
With no argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");
With String argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
.withArguments(anyString()).thenReturn("mocked result");
Something to Consider
Make sure the private function is calling another public function and you can proceed only mocking the public function.
Using java version 1.7.0_05
When i compile the below code it's give me testpackage could not be found error.
But if i remove the static keyword from "import static testpackage.TestStatic;" it's compiling successfully.
Test:
import java.io.*;
import java.util.*;
import static testpackage.TestStatic;
import static java.lang.Integer.MAX_VALUE;
public class Test {
public static void main(String args[]) {
System.out.println("hello world");
System.out.println("Maximum value of int variable using " +
"static import : "
+ MAX_VALUE);
}
}
TestStatic:
package testpackage;
import java.io.*;
import java.util.*;
public class TestStatic {
public static void testStatic() {
System.out.println("Inside Test Static");
}
public void testNormal(){
System.out.println("test normal");
}
public static void main(String args[]) {
System.out.println("hello world");
}
}
import static is for importing static members of classes, not whole classes. You could say "import static testpackage.TestStatic.testStatic;".
EDIT: fixed syntax
When you say import static testpackage.TestStatic; the compiler does not know what you want to import, you could mean import a static variable TestStatic in a class testpackage. In fact, I think you wanted to import testStatic() from the testpackage.TestStatic class,
For a method or field by name
import static testpackage.TestStatic.testStatic;
For all static methods and fields
import static testpackage.TestStatic.*;
I have a class which I would like to test with a public method that calls private one. I'd like to assume that private method works correctly. For example, I'd like something like doReturn....when.... I found that there is possible solution using PowerMock, but this solution doesn't work for me.
How It can be done? Did anybody have this problem?
I don't see a problem here. With the following code using the Mockito API, I managed to do just that :
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
And here's the JUnit test :
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 static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
#RunWith(PowerMockRunner.class)
#PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
#Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());
when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
.withArguments(anyString(), anyInt())
.thenReturn(true);
spy.meaningfulPublicApi();
}
}
A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.
Change your private method to protected.
In your test class extend the class
override the previously-private method to return whatever constant you want
This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.
To mock a private method directly, you'll need to use PowerMock as shown in the other answer.
For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.
import java.util.Random;
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
The test class looks as follows:
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 static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;
#RunWith(PowerMockRunner.class)
#PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
private CodeWithPrivateMethod classToTest;
#Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
classToTest = PowerMockito.spy(classToTest);
doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());
classToTest.meaningfulPublicApi();
}
}
i know a way ny which you can call you private function to test in mockito
#Test
public void commandEndHandlerTest() throws Exception
{
Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
retryClientDetail_privateMethod.setAccessible(true);
retryClientDetail_privateMethod.invoke(yourclass.class, null);
}
With no argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");
With String argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
.withArguments(anyString()).thenReturn("mocked result");
Something to Consider
Make sure the private function is calling another public function and you can proceed only mocking the public function.