I'm testing dao layer. Before insert entity I must initialize DataSource context.xml but it described in web.xml
<resource-ref>
<res-ref-name>jdbc/MyChat</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
when I run tests I have an error
Running dao.UserDaoTest
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.fact
ory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.art.utils.ConnectionPool.<init>(ConnectionPool.java:21)
at com.art.dao.impl.DaoFactoryImpl.<init>(DaoFactoryImpl.java:18)
at dao.UserDaoTest.init(UserDaoTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Please, tell me, what I must to do, that solved this problem?
This is my code
public class DaoFactoryImpl implements DaoFactory {
private ConnectionPool connectionPool;
public DaoFactoryImpl() {
connectionPool = new ConnectionPool();
}
private Connection getConnection(){
try {
return connectionPool.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public UserDaoImpl getUserDao() {
return new UserDaoImpl(getConnection());
}
public SecurityUserDaoImpl getSecurityDao() {
return null;
}
}
public abstract class BaseDaoTest {
protected DaoFactory daoFactory;
#Before
public void init(){
daoFactory = new DaoFactoryImpl();
}
}
public class UserDaoTest extends BaseDaoTest{
private UserDaoImpl userDao;
private User user;
#Before
public void init(){
userDao = daoFactory.getUserDao();
SecurityUserDaoImpl securityDao = daoFactory.getSecurityDao();
SecurityUserCredentials security = new SecurityUserCredentials();
security.setAuthToken("TestToken");
security.setRole(UserRole.REGISTER_USER);
security.setActivate(true);
SecurityUserCredentials resultSecurity = securityDao.create(security);
user = new User();
user.setSecurity(resultSecurity);
user.setLogin("TestLogin");
user.setPassword("TestPass");
}
#Test
public void testAddUserInDataBase(){
User testUser = userDao.create(user);
assertNotNull(testUser);
assertEquals(testUser.getLogin(), "TestLogin");
assertEquals(testUser.getPassword(), "TestPass");
}
}
Related
I'm trying to test a method in service class which uses ModelMapper to convert entity to dto, but I'm getting NullPointerException at this line mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); in the service class.
Exception
java.lang.NullPointerException
at pro.budthapa.service.impl.StockCategoryServiceImpl.getStockCategoryByIdAndBusinessGroupId(StockCategoryServiceImpl.java:56)
at pro.budthapa.service.impl.StockCategoryServiceImplTest.WhenCategoryPresent_ShouldReturnCategory(StockCategoryServiceImplTest.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Test Class
#RunWith(MockitoJUnitRunner.class)
public class StockCategoryServiceImplTest {
#Mock
private ModelMapper mapper;
#Mock
private StockCategoryRepository stockCategoryRepository;
#InjectMocks
private StockCategoryServiceImpl stockCategoryService;
#Before
public void setup() {
mapper = new ModelMapper();
}
#Test
public void WhenCategoryPresent_ShouldReturnCategory() throws Exception {
int bgId = 10;
int categoryId = 5;
StockCategory sc = new StockCategory();
sc.setCategoryId(categoryId);
sc.setBusinessGroupId(String.valueOf(bgId));
sc.setDescription("Test Item");
Mockito.when(stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId))).thenReturn(Optional.of(sc));
StockCategoryDto result = stockCategoryService.getStockCategoryByIdAndBusinessGroupId(categoryId, bgId);
assertEquals(5, result.getCategoryId() );
assertEquals(10, result.getBusinessGroupId());
assertNotNull(result.getDescription());
Mockito.verify(stockCategoryRepository, Mockito.times(1)).findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
}
}
Service Class
#Service
public class StockCategoryServiceImpl implements StockCategoryService {
private ModelMapper mapper;
private StockCategoryRepository stockCategoryRepository;
public StockCategoryServiceImpl(ModelMapper mapper, StockCategoryRepository stockCategoryRepository) {
this.mapper = mapper;
this.stockCategoryRepository = stockCategoryRepository;
}
#Override
public StockCategoryDto getStockCategoryByIdAndBusinessGroupId(int categoryId, int bgId) {
Optional<StockCategory> cat = stockCategoryRepository.findByCategoryIdAndBusinessGroupId(categoryId, String.valueOf(bgId));
if(cat.isPresent()) {
//getting NullPointerException at this line
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
return mapper.map(cat.get(), StockCategoryDto.class);
}
StockCategoryDto dto = new StockCategoryDto();
dto.setMessage("Category not found for given id: "+categoryId);
return dto;
}
}
You shouldn't reassign your mocked ModelMapper in setup method. Remove this method
And I can't find in your code mock definition for mapper.getConfiguration()
when(mapper.getConfiguration()).thenReturn(...)
You should tell it to mockito.
Here is my test method:
#Test
public void shouldReturnUser_whenPassedUser() {
// given
when(userStub.getUsername()).thenReturn(defaultName);
when(userStub.getPassword()).thenReturn(defaultPassword);
when(userStub.getEmail()).thenReturn(defaultEmail);
// when
User savedUser = userServiceBean.saveUser(userStub);
// then
assertNotNull(savedUser);
verify(userRepository, times(1)).save(any(User.class));
}
Here is my setup:
#Spy
#InjectMocks
private UserServiceBean userServiceBean;
#Mock
private UserRepository userRepository;
#Mock
private Principal principal;
#Mock
private PasswordEncoder passwordEncoder;
#Mock
private User userStub;
private String defaultName = "user";
private String defaultPassword = "password";
private String defaultEmail = "example#example.com";
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
And here is my userService.saveUser method:
public User saveUser(User user) {
User newUser = new User(user.getUsername(), user.getEmail(), passwordEncoder.encode(user.getPassword()));
return userRepository.save(newUser);
}
And my test results:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertNotNull(Assert.java:712)
at org.junit.Assert.assertNotNull(Assert.java:722)
at com.doublemc.services.UserServiceBeanTest.shouldReturnUser_whenPassedUser(UserServiceBeanTest.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Why does my method return null? I'm using a stubUser and I tell him exactly what to return to each getter (as I'm doing in my saveUser method) and it still returns null? How should I change that test to work?
You forgot to define the mock behaviour for the userRepository mock. So Mockito uses the default return value null for save.
Define the behaviour like this:
when(userRepository.save(any(User.class))).thenReturn(new User("saved name", "saved email", "saved password"));
I have the below test class, which has been stripped to the bare minimum needed to reproduce the issue:
#RunWith(Parameterized.class)
#ContextConfiguration(locations = { "classpath:restful-service-test-context.xml" })
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ResftulServiceTest {
#Autowired
#Qualifier("failedAspectTestMessage")
private String failedAspectTestMessage;
#Autowired
private ProviderService ProviderService;
private String methodName;
private Set valuesToReturnByMock;
private TestContextManager testContextManager;
public ResftulServiceTest(String methodName, String[] valuesToReturnByMockArray) {
this.methodName = methodName;
this.valuesToReturnByMock = new HashSet<>(Arrays.asList(valuesToReturnByMockArray));
}
#Parameterized.Parameters
public static Collection values() {
return Arrays.asList(new Object[][] { { "getCountries", new String[] { "GB", "US" } }, });
}
#Before
public void setUpSpringContext() throws Exception {
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
}
#Test
public void testGetValues_Fail_MyException() throws Exception {
Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);
Mockito.when(methodInProviderService.invoke(ProviderService))
.thenThrow(new MyException(failedAspectTestMessage, StatusCodeType.ERROR));
}
#Test
public void testGetValues_Fail_Exception() throws Exception {
Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);
Mockito.when(methodInProviderService.invoke(ProviderService))
.thenThrow(new AspectException(failedAspectTestMessage));
}
}
If I run each of the tests separately, they work fine. However, if I run all of them, testGetValues_Fail_Exception fails on the Mockito line with error:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com<obfuscated>.ResftulServiceTest.testGetValues_Fail_Exception(ResftulServiceTest.java:111)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: com.<obfuscated>.MyException: FAILED_ASPECT_TEST_MESSAGE
... 40 more
If I replace the .thenThrow in testGetValues_Fail_MyException with .thenReturn, it all works fine, so at some point the isolation is being broken. How can I fix this problem?
Try using Mockito.reset() passing your mock. Usually this is done to prevent interaction between test. It resets the previously configured behavior of the mock. However, in your case I cannot give more details as you are using an unusual combination of Parameterized with Spring context and DirtiesContext.
I am trying to write an automation framework using Java and selenium. While running Junit tests, Firefox browser starts but it cannot go to my local site. I get a NullPointer Exception. I am new to Java, any help will be greatly appreciated. Thanks
java.lang.NullPointerException
at WordpressFramework.LoginPage.GoTo(LoginPage.java:18)
at WordpressTest.LoginTests.Admin_User_Can_Log_In(LoginTests.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
public class LoginTests {
#Before
public void Init()
{
Driver_Setup.Initialize();
}
#Test
public void Admin_User_Can_Log_In(){
LoginPage.GoTo();
LoginPage.LoginAs("rizwan").WithPassword("*****").Login();
public class Driver_Setup {
private static WebDriver instance;
public static WebDriver getWebDriver() {
return instance;
}
public static void setWebDriver(WebDriver instance) {
Driver_Setup.instance = instance;
}
public static void Initialize()
{ WebDriver webdriver=new FirefoxDriver();
webdriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); }
}
public class LoginPage {
public static void GoTo() {
Driver_Setup.getWebDriver().navigate().to("http://localhost:57464/wp-login.php");
}
public static LoginCommand LoginAs(String username)
{
return new LoginCommand(username);
}
public static class LoginCommand
{
private String username;
private String password;
public LoginCommand(String username)
{
this.username = username;
}
public LoginCommand WithPassword(String password) {
this.password= password;
return this;
}
public void Login() {
WebElement loginInput = Driver_Setup.getWebDriver().findElement(By.id("user_login"));
loginInput.sendKeys(username);
WebElement passwordInput = Driver_Setup.getWebDriver().findElement(By.id("user_pass"));
WebElement loginButton = Driver_Setup.getWebDriver().findElement(By.id("wp-submit"));
loginButton.click();
}
}
Looks like the problem is inside Driver_Setup class - getWebDriver returns null since you have not called setWebDriver() to set the instance value.
I have rest service(PUT) which I intend to unit test it. I am using RestEasy for the Rest calls.
Here is my Resource :
#Path("/my_person")
public class MyResource {
private MyDAO myDao;
#Inject
public MyResource(MyDao myDao) {
this.myDao = myDao;
}
#PUT
#Timed
#Path("purchase_number/{purchaseNumber}/amount/{amount}/number_of_items")
#Produces(MediaType.APPLICATION_JSON)
public Response getItems(#PathParam("purchaseNumber") String purchaseNumber,
#PathParam("amount") String amount) {
return Response.ok(String.format("{\"items\": %d}", myDao.getItems(purchaseNumber, amount))).build();
}
}
The myDao.getItems returns an integer.
My Test class is as follows :
#RunWith(MockitoJUnitRunner.class)
public class MyResourceTest {
#Mock
private MyDao myDao;
#InjectMock
private MyResource myResource;
private TJWSEmbeddedJaxrsServer server;
private ResteasyClient resteasyClient;
#Before
public void startServer() throws IOException {
resteasyClient = new ResteasyClientBuilder().build();
server = new TJWSEmbeddedJaxrsServer();
server.setPort(PORT);
server.setBindAddress("localhost");
server.getDeployment().getResources().add(myResource);
server.start();
}
#After
public void stopServer() {
if (server != null) {
server.stop();
server = null;
}
}
#Test
public void testWhenValidInputGiven() {
String purchaseNumber = "A57697DF";
String amount = "340";
when(myDao.getItems(purchaseNumber, amount)).thenReturn(10);
Response response = resteasyClient.target("http://localhost:9980/my_person/purchase_number/{purchaseNumber}/amount/{amount}/number_of_items").request().buildPut(Entity.entity("{}", MediaType.APPLICATION_JSON))).invoke();
String text = response.getEntity().toString();
assertEquals(200, resp.getStatus());
assertEquals("{\"items\": 10}", text);
}
}
I get the following error at String text = response.getEntity().toString() since the entity object is null. So does it mean that it didn't create the request at all?
java.lang.NullPointerException
at resources.MyResourceTest.testWhenValidInputGiven(MyResourceTest.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:427)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:376)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.tjws.TJWSServletDispatcher.service(TJWSServletDispatcher.java:40)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at Acme.Serve.Serve$ServeConnection.runServlet(Serve.java:2331)
at Acme.Serve.Serve$ServeConnection.parseRequest(Serve.java:2285)
at Acme.Serve.Serve$ServeConnection.run(Serve.java:2057)
at Acme.Utils$ThreadPool$PooledThread.run(Utils.java:1402)
at java.lang.Thread.run(Thread.java:745)
Have you tried to put / in front of you method path #Path("/purchase_number/{purchaseNumber}/amount/{amount}/number_of_items")
i think the framework misunderstood your path and expect my_personpurchase_number/.
Check your status code on response to see if actually get 200 back or a 404.
The solution to this problem was that I was using
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
instead of
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<version>3.0.10.Final</version>
</dependency>
both had the class javax.ws.rs.core.Response.