Topic: Java JUnit Testing I\'m having problems getting some unit tests to pass.
ID: 3879579 • Letter: T
Question
Topic: Java JUnit Testing
I'm having problems getting some unit tests to pass. Help will be greatly appreciated!
Here is the code:
==============================================================
import com.fasterxml.jackson.databind.node.ObjectNode;
public interface HelloWorld{
public ObjectNode StartHelloWorld(ObjectNode tbd);
public ObjectNode ContinueHelloWorld(ObjectNode tbd);
public Boolean EndHelloWorld(ObjectNode tbd);
}
====================================================
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.stereotype.Component;
@Component
public class HelloWorldImplementation implements HelloWorld{
@Override
public ObjectNode StartHelloWorld(ObjectNode tbd){
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ObjectNode ContinueHelloWorld(ObjectNode tbd){
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Boolean EndHelloWorld(ObjectNode tbd){
throw new UnsupportedOperationException("Not supported yet.");
}
}
====================================================
Below is what I have so far but it keeps failing. Also, I haven't come up with an idea to even check the third implemented method that is a boolean. All the methods at the moment only throw Exceptions and that's all they are supposed to do for now. If someone can show me how to have all three pass with a brief explanation so I can understand unit testing better, it would be appreciated. Thanks in advance!
-MV
//The test code I have written so far that doesn't work
@RunWith(MockitoJUnitRunner.class)
public class HelloWorldTest{
@Rule
public ExpectedException thrown= ExpectedException.none();
@InjectMocks
private HelloWorldImplementation hwi;
@Test(expected=Exception.class)
public void TestStartHelloWorld() throws Exception{
thrown.expect(UnsupportedOperationException.class);
throw.expectMessage("Not supported yet.");
}
}
Explanation / Answer
Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception
So your code is here :
@RunWith(MockitoJUnitRunner.class)
public class HelloWorldTest{
@InjectMocks
private HelloWorldImplementation hwi;
@Test
public void TestStartHelloWorld() {
when(hwi).EndHelloWorld();
then(caughtException()).isInstanceOf(UnsupportedOperationException.class);
}
}
this is the example i have added for EndHelloWorld fuction.
I hope this answered your question. Many Thanks.
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static com.googlecode.catchexception.CatchException.caughtException; import static com.googlecode.catchexception.apis.BDDCatchException.then; import static com.googlecode.catchexception.apis.BDDCatchException.when; import static org.mockito.BDDMockito.given;