Cannot find symbol, JUnit, Enum method - java
Hello at the risk of looking stupid I am having problem with Junit but I am at the stage where i do not care anymore.
I am trying to write a "simple" JUnit test for a Enum and I am almost tearing my hair out of frustration.
I get the famous error "cannot find symbol" when i try to call my methods in my public Enum. I feel like I am doing everything right and I do not understand what I am missing.
I have browsed Stackoverflow for quiet some time and have seen alot of people asking similar questions but I could not find any relevant solution to my problem.
I feel like this should be a reletive easy problem to spot if you are a experienced programmer but i have sat with this code for to long and cannot see the problem.
I would greatly appreciate if someone could point out the reason before I become bald...
// EDIT 1: Added package in Enum
// EDIT 2: Copied same code to Eclipse and the method is visible and i can run the test. I assume this is not a syntax problem but a internal error with the editor which is Netbeans in my case.
Case closed i suppose.
// EDIT 3: Added Netbeans tag
Here is my Enum:
package chess.domain;
import java.util.stream.Stream;
public enum Position {
A8(1,8), B8(2,8), C8(3,8), D8(4,8), E8(5,8), F8(6,8), G8(7,8), H8(8,8),
A7(1,7), B7(2,7), C7(3,7), D7(4,7), E7(5,7), F7(6,7), G7(7,7), H7(8,7),
A6(1,6), B6(2,6), C6(3,6), D6(4,6), E6(5,6), F6(6,6), G6(7,6), H6(8,6),
A5(1,5), B5(2,5), C5(3,5), D5(4,5), E5(5,5), F5(6,5), G5(7,5), H5(8,5),
A4(1,4), B4(2,4), C4(3,4), D4(4,4), E4(5,4), F4(6,4), G4(7,4), H4(8,4),
A3(1,3), B3(2,3), C3(3,3), D3(4,3), E3(5,3), F3(6,3), G3(7,3), H3(8,3),
A2(1,2), B2(2,2), C2(3,2), D2(4,2), E2(5,2), F2(6,2), G2(7,2), H2(8,2),
A1(1,1), B1(2,1), C1(3,1), D1(4,1), E1(5,1), F1(6,1), G1(7,1), H1(8,1);
private final int COLUMN;
private final int ROW;
Position(int col, int row) {
this.COLUMN = col;
this.ROW = row;
}
public int getCOLUMN() {
return this.COLUMN;
}
public int getROW() {
return this.ROW;
}
public Stream<Position> getColumn(Position position){
return Stream.of(Position.values()).filter(pos -> (pos.getCOLUMN()) == position.getCOLUMN());
}
public Stream<Position> getRow(Position position){
return Stream.of(Position.values()).filter(pos -> (pos.getROW()) == position.getROW());
}
}
And here is my test:
package chess.domain;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PositionTest {
public PositionTest() {
}
#BeforeAll
public static void setUpClass() {
}
#AfterAll
public static void tearDownClass() {
}
#BeforeEach
public void setUp() {
}
#AfterEach
public void tearDown() {
}
/**
* Test of getCOLUMN method, of class Position.
*/
#Test
public void testGetCOLUMN() {
int expectedColumn = 1;
int actualColumn = Position.A8.getCOLUMN(); // ERROR IS LOCATED HERE ON METHOD "getCOLUMN"
assertEquals(expectedColumn, actualColumn);
}
/**
* Test of getROW method, of class Position.
*/
#Test
public void testGetROW() {
int expectedRow = 1;
int actualRow = Position.H1.getROW(); // ERROR IS LOCATED HERE ON METHOD "getROW"
assertEquals(expectedRow, actualRow);
}
}
Related
How to mock if condition using JUnit?
I am trying to mock a method using mockito. How to mock if condition using mockito? Here is my code #Override public RemedyWrapperOutput createRemedyTicket(RemedyWrapperInput remedyWrapperInput) throws Exception { logger.info("Inside createRemedyTicket"); RemedyWrapperOutput result = new RemedyWrapperOutput(); final RemedyRecord remData = remedyDao.getByApiAndTitle(remedyWrapperInput.getInstance(), remedyWrapperInput.getTitle()); /** * if no records exists in the DB or if the RemedyStatus is * CLOSED/RESOLVED/CANCELLED, we create a new ticket. */ if (remData == null ||remData.getStatus().equals(RemedyStatus.RESOLVED) || remData.getStatus().equals(RemedyStatus.CLOSED)|| remData.getStatus().equals(RemedyStatus.CANCELLED)) { createRemedyTicket(remedyWrapperInput, result); } else { /* If record exists check if its within duration */ /** * If not within time range create a ticket if New and Assigned * status. For all other status stop processing. */ if (!checkIfInTimeRange(remData.getCreationDateTime())) { if (remData.getStatus() != null && (remData.getStatus().equals(RemedyStatus.NEW) || remData.getStatus().equals(RemedyStatus.ASSIGNED) || remData.getStatus().equals(RemedyStatus.PENDING) || remData.getStatus().equals(RemedyStatus.IN_PROGRESS))) { int id = remedyDao.create(createRemedyInput(remedyWrapperInput, remData)); callRemedyRestApi(remedyWrapperInput, result, id); result.setMessage("Remedy request submitted"); } } else { result.setMessage("A request of this category has already been logged inside specified time range."); } // Update the last update time to current time remedyDao.update(remData); } return result; }
I think you want to look at the method you are trying to mock. Rather than the contents of the method. Let me explain using an example. Here is a simple class that I want to test: package com.diffblue.javademo; public class ClassToTest { private boolean beenChecked = false; private SomeDAO someDAO = new SomeDAO(); public void checkActive(int id) { if (someDAO.isActive(id)) { beenChecked = true; } } public boolean getBeenChecked() { return beenChecked; } } It makes a call to SomeDAO which I want to mock: package com.diffblue.javademo; public class SomeDAO { public boolean isActive(int id) { if (id < 5) { return true; } return false; } } When I am creating a test case I think about the path through checkActive that I want to test and then pick an answer from isActive that will exercise that path. For example: package com.diffblue.javademo; import org.junit.Assert; import org.junit.Test; import org.mockito.Matchers; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import static org.mockito.Mockito.when; public class ClassToTestTest { /** * Test the positive side of the if statement in checkActive */ #PrepareForTest({SomeDAO.class}) #Test public void positiveTest() throws Exception { // Arrange ClassToTest objectUnderTest = new ClassToTest(); SomeDAO someDAO = PowerMockito.mock(SomeDAO.class); when(someDAO.isActive(Matchers.anyInt())).thenReturn(true); int activeId = 3; // Act objectUnderTest.checkActive(activeId); // Assert Assert.assertTrue(objectUnderTest.getBeenChecked()); } } In this case, I have checked the path where the if statement (line 6 of SomeDAO) is true. So I haven't mocked the if statement, but I have forced a particular code path by carefully selecting the return values that Mockito is giving.
Testing class that insert, update and delete from the db
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"); } }
Sonar rule S2699: Not all asserts are recognized as valid assertions
We are running Sonarqube 5.6.1 with the Java Plugin 4.1 and having some troubles using the Sonar rule S2699 (Test should include assertions). Using this example test class import mypackage.Citit1543Dummy; import mypackage.Citit1543OtherDummy; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import java.util.Arrays; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isIn; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.IsNot.not; import static org.mockito.Matchers.notNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.junit.Assert.assertThat; public class Citit1543Test { #Before public void setUp() { MockitoAnnotations.initMocks(this); } #Test public void test1() { assert true; } #Test public void test2() { Assert.assertTrue(1 > (2-3)); } #Test public void test3() { Assert.assertFalse(1 > (100-1)); } #Test public void test4() { Assert.assertThat("test", 1, is(1)); } #Test public void test5() { Assert.assertArrayEquals(new String[0], new String[0]); } #Test public void test6() { Assert.assertEquals(1 > 0, true); } #Test public void test7() { // asserts in another method test7asserts(1, 1); } private void test7asserts(int a, int b) { Assert.assertTrue(a == b); } #Test public void test8() { test8asserts(1, 2); } private void test8asserts(int a, int b) { Assert.assertNotSame(a, b); } #Test public void test9() { Citit1543Dummy dummy = new Citit1543Dummy(); dummy.otherDummy = mock(Citit1543OtherDummy.class); dummy.doSomething(); verify(dummy.otherDummy, times(1)).doSomething(); } #Test public void test10() { Citit1543Dummy dummy = new Citit1543Dummy(); dummy.otherDummy = mock(Citit1543OtherDummy.class); dummy.doSomething(); test10verifies(dummy.otherDummy); } private void test10verifies(Citit1543OtherDummy otherDummy) { verify(otherDummy, times(1)).doSomething(); } #Test public void test11() { Assert.assertThat("test", "", not(1)); } #Test public void test12() { Assert.assertThat("test", 1, lessThan(2)); } #Test public void test13() { Long[] arr = new Long[] { 1L, 2L, 3L, 4L }; assertThat("Just testing", arr, is(new Long[] { 1L, 2L, 3L, 4L })); } } our Sonarqube instance flags the test cases test1 (assert statement not recognized), test7 (assert statements in another method), test8 (same) , test10 (Mockitos verify in another method), test11 and test13 as methods without assertions. I'm pretty sure that there are a lot more methods which aren't recognized (yes, unfortunately we use a bunch of different mocking/testing framework across our projects). For now, we started to //NOSONAR whenever one of the asserts/verifies aren't recognized. Is there an easy way to include these methods to be recognized as valid asserts?
Many of your stated issues are known and indeed (in some form of another) marked as FP: test1: The current flow analysis ignores assert statements. See this post over at the groups. The cases test7, test8 and test10 are related to the lack of not having cross-procedural analysis: They are valid cases but the current flow doesn't know that (ex.) test7assert is a valid assert statement for another method. See this post over at the groups. Your other cases also produce false positives in the tests of S2699. I'd expect that once a SonarSource dev reads this topic that they'll create a ticket to resolve the cases in test11/13. But as I'm not a dev of them I can't guarantee that of course. As to : Is there an easy way to include these methods to be recognized as valid asserts? No, the valid assertions are defined within the code of S2699 and are not a parameter. Some of your cases will require a more complex flow analysis whilst the last couple just seem to boil down to some missing definitions or too strict definitions, but I didn't deep-dive into the reasons why they produce FPs.
Java.beans.Introspector.getBeanInfo() fails to assign writeMethods
I made a super simple example that doesn't make any sense. public static void main(String [] args) throws IntrospectionException { BeanInfo info = Introspector.getBeanInfo(DemandBidType.class); int breakpoint = 0; } Here's my class: public class DemandBidType { protected Boolean isDuplicateHour; protected Boolean test; public boolean isIsDuplicateHour() { return isDuplicateHour; } public void setIsDuplicateHour(Boolean isDuplicateHour) { this.isDuplicateHour = isDuplicateHour; } public Boolean getTest() { return test; } public void setTest(Boolean test) { this.test = test; } } And here is a screen shot showing the problem; the field I care about isn't being recognized as having a write method. I added another field 'test' and that one works fine... There was very little related to this on Google, and what was there was years old with older java versions. You can see in the bottom right that I'm using 1.7.51. (http://i.stack.imgur.com/DKC6e.png)
It turns out it's because the return type of the getter doesn't match the argument of the setter. (One's "Boolean" the other "boolean").
Eclipse Junit run configuration that takes the current selected test class as an arg?
Instead of constantly creating identical debug configuraitons for my test cases, I would like to be able to simply save a few arguments common across all my Junit tests, right click on a specific test, then run that single run config. IE I would like a single debug configuration that can take as an argument the current selected test case instead of requiring me to manually specify it every time in the JUnit run configuration. My only options in the dialog appear to be either to specify a single test class or run all the tests in the project. As a result, Eclipse is littered with dozens of run configurations for all my test cases. Instead of specifying a specific test class, I'd like it to specify a variable like ${container_loc} or ${resource_loc} for the class to run as in this question. Is there a variable in Eclipse that specifies the current selected Java class that I could place in the test class field in the dialog? A specific example where this is useful is when running the Lucene unit tests. There's lots of arguments you can specify to customize the tests, some of which like -ea are required. Everytime I want to test a specific test case in Lucene in Eclipse, I have to manually setup these variables in the Eclipse debug config dialog :-/.
Have you looked at Parameterized Tests in JUnit? Here is an example: import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; #RunWith(Parameterized.class) public class ParamTest { #Parameters(name = "{index}: fib({0})={1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } }); } private int input; private int expected; public ParamTest(int input, int expected) { this.input = input; this.expected = expected; } #Test public void test() { Assert.assertEquals(expected, input); } } If you just want to run one test at a time you can use private variables as in: public class MultipleTest { private int x; private int y; public void test1(){ Assert.assertEquals(x, y); } public void test2(){ Assert.assertTrue(x >y); } public void args1(){ x=10; y=1; } public void args2(){ x=1;y=1; } public void args3(){ x=1;y=10; } #Test public void testArgs11(){ args1(); test1(); } #Test public void testArgs21(){ args2(); test1(); } #Test public void testArgs31(){ args3(); test1(); } #Test public void testArgs12(){ args1(); test2(); } #Test public void testArgs22(){ args2(); test2(); } #Test public void testArgs32(){ args3(); test2(); } }