Hello Every One I Have This Method Which it Checks if the Input String Is Numbers only And Its Return True Or False
I Want To Make A Junit Test For this method and Actually I Don't know how to test Method Like This Can Any One Help And Thank You All.
My Method:
private Boolean Check_Ean(String EAN_Ch)
{
Long EAN;
try
{
EAN = Long.parseLong(EAN_Ch);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
First you need to create a class in the test folder(located at the same path as main). Then you need to use their annotations to or either Prepare the information, Test and Destroy the information(usefull when you have DB connection opens or streams):
public class TestClass {
#Before
public void setup() {
//prepare information
}
#Test
public void testCheck_Ean() {
boolean result = Check_Ean(...);
Assert.assertTrue(result);
}
#After
public void destroy() {
//if you need to "destroy" some info
}
}
tester = new CLASS_NAME();
assertTrue(tester.Check_Ean("5");
assertFalse(tester.Check_Ean("this is noot a Long");
You might be overthinking it. Also the Check_Ean method maybe could be static if you pass the Ean as a parameter rather than getting a class variable.
Related
How can I test the following service method with Junit test? It's a very simple rebuild of my code and only an example.
I want to test in a JUnit test, what's happening, if the file string is empty or null.
Unfortunately I'm new to testing with JUnit. I read already some examples for rest controller and services and repos to me mocked and the methods for it, but here I have no idea how it could work. May someone can help?
public class MyService {
private String fileName = "src/main/resources";
// or
// private String fileName = ${modulename.config.filename};
// #Autowired
// private RepoService RepoService;
#EventListener
public void init(ContextRefreshedEvent event) {
try {
myMethod();
} catch (Exception e) {
// LOGGING
};
}
public void myMethod() {
if(fileName != null && !fileName.isEmpty()) {
// doSomething with file and IOException
// save in repo
} else {
// LOGGING
}
}
}
public void myMethod() {
if(fileName != null && !fileName.isEmpty()) {
// doSomething with IOException
} else {
// LOGGING
}
}
}
The test should look like the following. I tried to set the value somehow in the test, but it does not make sense and it's not set then.
#SpringBootTest
class DemoApplicationTests {
#Test
public void fileNameTest() {
// GIVEN
//Mockito.when()
// WHEN
// THEN
}
}
To change the value of a private variable Use Field modification using Reflection API.
Here's a nice explanation on how to do this.
I am trying to use argument capture to determine what arguments are being passed to a mocked Mockito method, but I am not able to capture any values.
class CombinedEvent
{
final List<String> events;
public CombinedEvent() {
this.events = new ArrayList<>();
this.events.add("WATCHITM");
this.events.add("BIDITEM");
}
}
Holder class
class CombinedNotificationAdapter {
private CombinedEvent combinedEvent;
CombinedNotificationAdapter() {
this.combinedEvent = new CombinedEvent();
}
public boolean isEnabled(String user, NotificationPreferenceManager preferenceManager) {
boolean status = true;
for (String event : combinedEvent.events) {
status = status && preferenceManager.isEventEnabled(user, event);
}
return status;
}
}
My unit test
#RunWith(JUnit4.class)
class CombinedNotificationAdapterTest {
private CombinedNotificationAdapter adapter;
#Mock
private NotificationPreferenceManager preferenceManager;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
adapter = new CombinedNotificationAdapter();
}
#Test
public void testIsEnabled() {
doReturn(true).when(preferenceManager).isEventEnabled(eq("test"), anyString());
Assert.assertTrue(adapter.isEnabled("test", preferenceManager));
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(preferenceManager, times(2)).isEventEnabled(eq("test"), captor.capture());
System.out.println(captor.getAllValues());
}
}
The output of captor.getAllValues() is an empty list. I would like the values to return a list of WATCHITM and BIDITEM. I don't know what I am going wrong.
Reference:
https://static.javadoc.io/org.mockito/mockito-core/2.28.2/org/mockito/Mockito.html#15
https://static.javadoc.io/org.mockito/mockito-core/2.6.9/org/mockito/ArgumentCaptor.html
I think you are overdoing:
doReturn(true)
. when(preferenceManager)
.isEventEnabled(eq("test"), anyString()):
You are scrubbing that expected method invocation and then combining that with your argument captor. And that does not work. You can either stub or capture, not both things! See this existing question for example.
My suggestion: look at this answer and learn how to create your own Answer object. Those get passed an instance of InvocationOnMock. And that class allows you to check the arguments passed into the mocked calls, too!
Refering to mock methods in same class
class Temp() {
public boolean methodA(String param) {
try {
if(methodB(param))
return true;
return false;
} catch (Exception e) {
e.printStackTrace();
}
}
}
The test class
#Test
public void testMethodA() {
Temp temp = new Temp();
Temp spyTemp = Mockito.spy(temp);
Mockito.doReturn(true).when(spyTemp).methodB(Mockito.any());
boolean status = temp.methodA("XYZ");
Assert.assertEquals(true, status);
}
When calling the real class temp to methodA should return the mocked method B value. Thus returning true. Why is this incorrect. I encounter the same problem.
I want to run the test on the real class and not for mock object as suggested by the answer. I want to run the class methodA and expect the mocked object spyTemp methodB value when it is called
Here is the Problem: methodA() you´re callint is from temp and you´ve defined a returning value from tempSPY.
So you need to call tempSpy.methodA() and then it´s returning the value of methodB() you´ve defined.
Here the solution if methodB() is public - spy temp/cut and call it this way:
// temp = cut
#Test
public void testMethodA_valid() {
// given
Temp spyTemp = Mockito.spy(temp);
boolean expected = true;
Mockito.doReturn(expected).when(spyTemp).methodB(Mockito.any(String.class));
// when
boolean actual = spyTemp.methodA("XYZ");
// then (faster readable)
Mockito.verify(spyTemp, times(1)).methodB(any(String.class))
Mockito.verifyNoMoreInteraction(<ALL YOUR MOCKS HERE>);
Assert.assertEquals(expected, is(equalTo(actual)));
}
If methodB() is private you can´t define what it should return. Then is´t just this and if error occures then methodB() got wrong behaviour:
#Test
public void testMethodA_valid() {
// given
boolean expected = true;
// when
boolean actual = temp.methodA("XYZ");
// then (faster readable)
Assert.assertEquals(expected, is(equalTo(actual)));
}
I have class that has 3 methods: insert, update and delete from the db.
In order to test it in the insert test method I need to use the insert method and after I insert i need to delete what I inserted, but in order to delete I should use the delete method that I also want to test so it didn't make sense to me that I need to use them and also test them.
I hope you understand my problem. Thanks in advance!
You must decide what you want to test. That was you describe, it is an integration test. By a “real” unitTest, you test only your method, and not the System method and not the database.
If you want a unitTest, you have several options. For Example, you work with interfaces and catch your statement before it comes to the database.
Edit 1 - one possibility to implement unit test with interfaces:
You need one interface that implements the method these go to the backend system:
public interface IDatabase{
public returnValue insert(yourParam);
public int update(yourParam);
}
Then you implement your method with the real functions in a class:
public class Database implements IDatabase {
#Override
public returnValue insert(yourParam) {
// do something
return null;
}
#Override
public int update(yourParam){
// do something
return 0;
}
}
This class you call in the main class:
/**
* The real class to do what you want to do.
*/
public class RealClass {
private IDatabase dbInstance = null;
private IDatabase getDbInstance() {
if (dbInstance == null) {
dbInstance = new Database();
}
return dbInstance;
}
protected void setDbInstance(IDatabase dataBase) {
dbInstance = dataBase;
}
public static void main(String[] args) {
getDbInstance().insert(yourParam);
}
}
For the unit test you implement the interface again:
public class UnitTest implements IDatabase {
#Override
public returnValue insert(yourParam) {
// Here can you test your statement and manipulate the return value
return null;
}
#Override
public int update(yourParam){
if (yourParam.containsValue(value1)) {
assertEquals("yourStatement", yourParam);
return 1;
}else if (yourParam.containsValue(value2)) {
assertEquals("yourStatement2", yourParam);
return 5;
}else{
assertTrue(false,"unknown Statement")
}
}
#Test
public void yourTest(){
RealClass.setDbInstance(this);
//Test something
}
}
This is time-consuming to implement, but with this, you are independent from the backend system and you can call the unittest every time without a database.
By default, the order of test methods is not warrantied in JUnit. Nevertheless, as of JUnit 4.11, you can order by the test name, as follows:
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Test1 {
#Test
public void aInsert() {
System.out.println("first INSERT");
}
#Test
public void bUpdate() throws Exception {
System.out.println("second UPDATE");
}
#Test
public void cDelete() throws Exception {
System.out.println("third DELETE");
}
}
My application have several execution modes, and in 1 mode it is normal that some of my tests will throw a concrete exception. I need to annotate this methods with something like #SkipOnFail that will set method as skipped if exception was thrown.
thanks in advance!
#Edit(for my question to be more clear)
#Test(expected=ConcreteException.class)
does not work for me because i need my tests to pass even if ConcreteException.class was not thrown(expected tag in junit will mark my test as failed if this exception won't be thrown), and to be skipped otherwise. In all other cases it should work as always.
#Solution that worked for me(junit v4.7) thx to #axtavt
#Rule
public MethodRule skipRule = new MethodRule() {
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
if(method.getAnnotation(SkipOnFail.class) == null) return base;
return new Statement() {
#Override
public void evaluate() throws Throwable {
try{
base.evaluate();
} catch (ConcreteException e) {
Assume.assumeTrue(false);
}
}
};
}
};
#Thx
I don't think that such a feature is available out of the box, but it should be pretty easy to implement with custom TestRule and Assume, something like this:
#Rule
public TestRule skipRule = new TestRule() {
public Statement apply(final Statement base, Description desc) {
if (desc.getAnnotation(SkipOnFail.class) == null) return base;
return new Statement() {
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (MyExceptoion ex) {
Assume.assumeTrue(false);
}
}
};
}
};
What about using JUnit Extensions?
The following example is taken from their Tutorial.
It provides aditional annotations for Prerequisites (#Prerequisite): Ignore tests based on conditions.
The required approach would be to check this during running tests. So you can simply add a #Prerequisite(requires="") annotation.
public class TestFillDatabase {
#Prerequisite(requires = "databaseIsAvailable")
#Test public void fillData() {
// ...
}
public boolean databaseIsAvailable() {
boolean isAvailable = ...;
return isAvailable;
}
}
public class TestFillDatabase {
#Prerequisite(requires = "databaseIsAvailable")
#Test public void fillData() {
// ...
}
public boolean databaseIsAvailable() {
boolean isAvailable = ...;
return isAvailable ;
}
}
This specified methods with #Prerequisite(requires = "databaseIsAvailable") must be a public method, returning a boolean or Boolean value.
If these methods will be consolidated in helper classes, you can also specify static methods within a class to be called using #Prerequisite(requires = "databaseIsAvailable", callee="DBHelper").
public class TestFillDatabase {
#Prerequisite(requires = "databaseIsAvailable", callee="DBHelper")
#Test public void fillData() {
// ...
}
}
public class DBHelper {
public static boolean databaseIsAvailable() {
boolean isAvailable = ...;
return isAvailable ;
}
}
Also using the Assume class (since jUnit 4.4), you can use assumeNoException():
try{
base.evaluate();
} catch (ConcreteException e) {
Assume.assumeNoException("Concrete exception: skipping test", e);
}
I searched for the docs about JUnit and it appears that from version 4.9 they have introduced what they call test rules (see TestRule). You may start from this.
The ExpectedException class marked as #Rule could be of some help in order to check for exceptions thrown but not mandatory for the test to pass.
For more advanced usage I cannot say for the moment as I've just discovered it.