Here is the class I want to test
@Component
public class PermissionCheck {
@Autowired
private MyEntityRepository myEntityRepository;
public boolean hasPermission(int myEntityID) {
MyEntity myEntity = myEntityRepository.findById(myEntityId);
return myEntity != null;
}
}
Here is the test class
@RunWith(SpringRunner.class)
public class PermissionCheckTests {
@MockBean
private MyEntityRepository myEntityRepository;
private PermissionCheck permissionCheck;
@Before
public void before() {
this.permissionCheck = new PermissionCheck();
}
@Test
public void shouldHasPermission() {
MyEntity myEntity = new MyEntity();
when(this.myEntityRepository.findById(any())).thenReturn(myEntity);
assertTrue(this.permissionCheck.hasPermission(0));
}
}
And when I run this test I got
java.lang.NullPointerException
at PermissionCheck.hasPermission(PermissionCheck.java:line1)
at PermissionCheckTests.shouldHasPermission(PermissionCheckTests.java:line2)
In the above, line1 and line2 refer to these two lines
MyEntity myEntity = myEntityRepository.findById(myEntityId);
assertTrue(this.permissionCheck.hasPermission(0));
And using debugger I see that when entering PermissionCheck.hasPermission from PermissionCheckTests.shouldHasPermission, the repository field
@Autowired
private MyEntityRepository myEntityRepository;
is null.
I created these classes by referring to others existing codes, from different places, and without really understanding how to the annotations (partially due to running out of time), so if someone can tell me not only how to fix, but also why I'm wrong, I would really appreciate it!
Aucun commentaire:
Enregistrer un commentaire