I have an HTTPClient test for my spring boot app. I have a class that throws an exception if the a POST request to the server is in a string 2048 bytes or over.
#Component
public class ApplicationRequestSizeLimitFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println(request.getContentLength());
if (request.getContentLengthLong() >= 2048) {
throw new IOException("Request content exceeded limit of 2048 bytes");
}
filterChain.doFilter(request, response);
}
}
I created a unit test for it but I am not sure how I can write an assert statement to check if it fails to post the request.
Right now I have this so far in my test class
#Test
public void testSize() throws ClientProtocolException, IOException {
Random r = new Random(123);
long start = System.currentTimeMillis();
String s = "";
for (int i = 0; i < 65536; i++)
s += r.nextInt(2);
String result = Request.Post(mockAddress)
.connectTimeout(2000)
.socketTimeout(2000)
.bodyString(s, ContentType.TEXT_PLAIN)
.execute().returnContent().asString();
}
This test fails which is what I want but I want to create an assert so it passes (assert that it fails the http response due to being over the byte limit).
You can surround the failing part with a try/catch, and call fail() at the end of the try block. If an exception is thrown, the fail() instruction should not be reached, and your test should pass.
#Test has an argument to assert that a particular exception gets thrown, you could write your test like e.g :
#Test(expected = IOException.class)
public void testSize() throws ClientProtocolException, IOException {
...
}
There are 3 ways you can achieve that:
1) Use #Test(expected = ....) annotation where you provide class of exception you want to check.
#Test(expected = IOException.class)
public void test() {
//... your test logic
}
This is not a recommended way of exception testing unless your test is really really small and does one thing only. Otherwise, you may get an IOException thrown but you won't be sure which part of test code exactly caused it.
2) Use #Rule annotation with ExpectedException class:
#Rule
public ExpectedException exceptionRule = ExpectedException.none();
#Test
public void testExpectedException() {
exceptionRule.expect(IOException.class);
exceptionRule.expectMessage("Request too big.");
//... rest of your test logic here
}
Please note that exceptionRule has to be public.
3) And last one, quite old-fashioned way:
#Test
public void test() {
try {
// your test logic
fail(); // if we get to that point it means that exception was not thrown, therefore test should fail.
} catch (IOException e) {
// if we get here, test is successfull and code seems to be ok.
}
}
It's an old fashioned way that adds some unnecessary code to your test that is supposed to be clean.
There is another solution, not already presented in these answers, and is my personal preference. assertThatThrownBy
in your case
#Test
public void testSizeException(){
assertThatThrownBy(()-> Request.Post(mockAddress)
.connectTimeout(2000)
.socketTimeout(2000)
.bodyString(s, ContentType.TEXT_PLAIN)
.execute().returnContent().asString())
.isInstanceOf(IOException.class)
.hasMessageContaining("Request content exceeded limit of 2048
bytes");
}
*Disclaimer, above code written directly into SO editor
Related
How can I test assertion immediately following an exception with EasyMock?
For example, there is a method storeIntoFile() which retrieves an object and writes it into a file. In case of an exception, this file is deleted. I'm looking to test this method specifically to verify that the file gets deleted on encountering an exception.
I have the following test to do this:
#Test (expected IOException.class)
public void testConnectionFailure throws IOException {
File storeFile = File.createTempFile(
"test",
"test"
);
storeIntoFile(storeFile);
Assert.assertFalse(storeFile.exists());
}
However in this case, the test completes as soon as the exception is encountered during the storeIntoFile call and does not proceed to test the following assertion. How can I test this assertion after the exception without using mock objects?
It's more a JUnit question than EasyMock. With JUnit 4.13, you can do the following.
public class MyTest {
public interface FileRepository {
void store(File file) throws IOException;
}
private void storeIntoFile(File file) throws IOException {
try {
repository.store(file);
} catch(IOException e) {
file.delete();
throw e;
}
}
private final FileRepository repository = mock(FileRepository.class);
#Test
public void testConnectionFailure() throws IOException {
File storeFile = File.createTempFile("test", "test");
IOException expected = new IOException("the exception");
repository.store(storeFile);
expectLastCall().andThrow(expected);
replay(repository);
IOException actual = assertThrows(IOException.class, () -> storeIntoFile(storeFile));
assertSame(expected, actual);
assertFalse(storeFile.exists());
}
}
I do not recommend the expected exceptions. assertThrows is much better since it allows to assert on the exception.
Hello guys I was wondering if this way of testing my exception is ok, i have this exception i need to throw in the second test annotation, im receiving as result a red evil bar, and a succeed and a failure, as you can guess the failure is my concern, i have a fail(); there but the reason is because i read thats the way to test the exception and now im confused.
Also i have to say im willin get the green bar because im expecting the exception, but i dont know if failure is the right way to see the answer of the expected exception.
Also if you had any advice, I would appreciate it
#Before
public void setUp() throws Exception {
LogPack.logPacConfig(Constants.LOGGING_FILE);
gtfri = "+RESP:GTFRI,380502,869606020101881,INCOFER-gv65,,10,1,1,0.0,0,888.1,-84.194560,9.955602,20170220074514,,,,,,0.0,,,,100,210100,,,,20170220074517,40A2$";
weirdProtocol = "+RESP:GRI,380502,869606020101881,INCOFER-gv65,,10,1,1,0.0,0,888.1,-84.194560,9.955602,20170220074514,,,,,,0.0,,,,100,210100,,,,20170220074517,40A2$";
factory = new LocomotiveFactory();
}
#Test
public void GTFRICreationTester_shouldPass() throws TramaConProtolocoloDesconocido {
assertTrue(factory.createLocomotive(gtfri, false, new Date()) instanceof LocomotiveGTFRI);
}
#Test(expected = TramaConProtolocoloDesconocido.class)
public void GTFRICreationTester_shouldFail() {
try {
factory.createLocomotive(weirdProtocol, false, new Date());
fail("Expected an TramaConProtolocoloDesconocido");
} catch (TramaConProtolocoloDesconocido e) {
//assertSame("exception thrown as expected", "no se conoce el protocolo dado para la creacion de este factory", e.getMessage());;
}
}
There is 3 most common ways to test expected exception:
First one is the most common way, but you can test only the type of expected exception with it. This test will fail if ExceptionType won't be thrown:
#Test(expected = ExceptionType.class)
public void testSomething(){
sut.doSomething();
}
Also you cannot specify the failure message using this approach
The better option is to use ExpectedException JUnit #Rule. Here you can assert much more for expected exception
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void testSomething(){
thrown.expect(ExceptionType.class);
thrown.expectMessage("Error message");
thrown.expectCause(is(new CauseOfExeption()));
thrown.reportMissingExceptionWithMessage("Exception expected");
//any other expectations
sut.doSomething();
}
The third option will allow you to do the same as with using ExpectedException #Rule, but all the assertion should be written manually. However the advantage of this method is that you can use any custom assertion and any assertion library that you want:
#Test
public void testSomething(){
try{
sut.doSomething();
fail("Expected exception");
} catch(ExceptionType e) {
//assert ExceptionType e
}
}
You can use ExpectedException which can provide you more precise information about the exception expected to be thrown with the ability to verify error message, as follows:
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
public class TestClass {
#Rule
public ExpectedException expectedException = ExpectedException.none();
#Test
public void GTFRICreationTester_shouldFail() {
expectedException.expect(TramaConProtolocoloDesconocido.class);
factory.createLocomotive(weirdProtocol, false, new Date());
}
}
To expolore more about it, you can refer to the blog written by me here - Expected Exception Rule and Mocking Static Methods – JUnit
if your are using java 8, I would recommend to go for the AssertJ library
public void GTFRICreationTester_shouldFail() {
assertThatExceptionOfType(EXCEPTION_CLASS).isThrownBy(() -> { factory.createLocomotive(weirdProtocol, false, new Date()) })
.withMessage("MESSAGE")
.withMessageContaining("MESSAGE_CONTAINING")
.withNoCause();
}
with that solution you can at one verify exception type, with message etc.
for more reading, take a look at:
http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion
You don't need to catch the Exception with try-catch
#Test(expected = TramaConProtolocoloDesconocido.class)
public void GTFRICreationTester_shouldFail() {
factory.createLocomotive(weirdProtocol, false, new Date());
}
If we suppose that factory.createLocomotive(weirdProtocol, false, new Date()) throws the exception when you apply a scenario that makes the exception thrown.
void createLocomotive(param...) {
//something...
throw new TramaConProtolocoloDesconocido();
}
I'm taking Software Testing because I'm majoring in CS. The professor gave us the source code of a program made in Java to test it. I'm testing right now this method:
public static void createPanel(HttpServletRequest req, HttpServletResponse res, HttpSession hs) throws IOException
{
String panelName = req.getParameter("panelName");
String panelDescription = req.getParameter("panelDescription");
int employeeID = ((EmployeeProfile)hs.getAttribute("User Profile")).EmployeeID;
boolean result;
//Let's validate our fields
if(panelName.equals("") || panelDescription.equals(""))
result = false;
else
result = DBManager.createPanel(panelName, panelDescription, employeeID);
b = result;
//We'll now display a message indicating the success of the operation to the user
if(result)
res.sendRedirect("messagePage?messageCode=Panel has been successfully created.");
else
res.sendRedirect("errorPage?errorCode=There was an error creating the panel. Please try again.");
}
I'm using Eclipse with JUnit and mockito to test all the methods including this one. For this specific method, I want to check if the program redirects to one location or another, but I don't know how to do it. Do you have any idea? Thanks.
You can actually achieve it easily with Mockito and ArgumentCaptor:
#RunWith(MockitoJUnitRunner.class)
public class MyTest {
#Mock
private HttpServletResponse response
...
#Test
public void testCreatePanelRedirection(){
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
YourClass.createPanel(request, response, session);
verify(response).sendRedirect(captor.capture());
assertEquals("ExpectedURL", captor.getValue());
}
}
I am trying to test file manipulation with my APP. First of all I wanna check that whenever I call a function that reads the file, this function will throw an Exception because the file isn't there.
However, I don't seem to understand how to achieve this... This is the code I designed, but it doesn't run ... the normal JUNIT says the FILEPATH wasn't found, the android JUNIT says, the Test could not be run.
The folder: /data/data/example.triage/files/ is already available in the virtual device...
#Before
public void setUp() throws Exception {
dr = new DataReader();
dw = new DataWriter();
DefaultValues.file_path_folder = "/data/data/example.triage/files/";
}
#After
public void tearDown() throws Exception {
dr = null;
dw = null;
// Remove the patients file we may create in a test.
dr.removeFile(DefaultValues.patients_file_path);
}
#Test
public void readHealthCardsNonExistentPatientsFile() {
try {
List<String> healthcards = dr.getHealthCardsofPatients();
fail("The method didn't generate an Exception when the file wasn't found.");
} catch (Exception e) {
assertTrue(e.getClass().equals(FileNotFoundException.class));
}
}
It doesn't look like you are checking for the exception in a way that correlates with the JUnit API.
Have you tried to make the call:
#Test (expected = Exception.class)
public void tearDown() {
// code that throws an exception
}
I don't think you want the setup() function to be able to generate an exception, since it is called before all other test cases.
Here's another way to test exceptions:
Exception occurred = null;
try
{
// Some action that is intended to produce an exception
}
catch (Exception exception)
{
occurred = exception;
}
assertNotNull(occurred);
assertTrue(occurred instanceof /* desired exception type */);
assertEquals(/* expected message */, occurred.getMessage());
So I would make you setup() code not throw an exception and move the exception generating code to a test method, using an appropriate way to test for it.
I have written a few JUnit tests with #Test annotation. If my test method throws a checked exception and if I want to assert the message along with the exception, is there a way to do so with JUnit #Test annotation? AFAIK, JUnit 4.7 doesn't provide this feature but does any future versions provide it? I know in .NET you can assert the message and the exception class. Looking for similar feature in the Java world.
This is what I want:
#Test (expected = RuntimeException.class, message = "Employee ID is null")
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() {}
You could use the #Rule annotation with ExpectedException, like this:
#Rule
public ExpectedException expectedEx = ExpectedException.none();
#Test
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("Employee ID is null");
// do something that should throw the exception...
System.out.println("=======Starting Exception process=======");
throw new NullPointerException("Employee ID is null");
}
Note that the example in the ExpectedException docs is (currently) wrong - there's no public constructor, so you have to use ExpectedException.none().
In JUnit 4.13 you can do:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
...
#Test
void exceptionTesting() {
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> { throw new IllegalArgumentException("a message"); }
);
assertEquals("a message", exception.getMessage());
}
This also works in JUnit 5 but with different imports:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
...
I like the #Rule answer. However, if for some reason you don't want to use rules. There is a third option.
#Test (expected = RuntimeException.class)
public void myTestMethod()
{
try
{
//Run exception throwing operation here
}
catch(RuntimeException re)
{
String message = "Employee ID is null";
assertEquals(message, re.getMessage());
throw re;
}
fail("Employee Id Null exception did not throw!");
}
Do you have to use #Test(expected=SomeException.class)? When we have to assert the actual message of the exception, this is what we do.
#Test
public void myTestMethod()
{
try
{
final Integer employeeId = null;
new Employee(employeeId);
fail("Should have thrown SomeException but did not!");
}
catch( final SomeException e )
{
final String msg = "Employee ID is null";
assertEquals(msg, e.getMessage());
}
}
Actually, the best usage is with try/catch. Why? Because you can control the place where you expect the exception.
Consider this example:
#Test (expected = RuntimeException.class)
public void someTest() {
// test preparation
// actual test
}
What if one day the code is modified and test preparation will throw a RuntimeException? In that case actual test is not even tested and even if it doesn't throw any exception the test will pass.
That is why it is much better to use try/catch than to rely on the annotation.
I never liked the way of asserting exceptions with Junit. If I use the "expected" in the annotation, seems from my point of view we're violating the "given, when, then" pattern because the "then" is placed at the top of the test definition.
Also, if we use "#Rule", we have to deal with so much boilerplate code. So, if you can install new libraries for your tests, I'd suggest to have a look to the AssertJ (that library now comes with SpringBoot)
Then a test which is not violating the "given/when/then" principles, and it is done using AssertJ to verify:
1 - The exception is what we're expecting.
2 - It has also an expected message
Will look like this:
#Test
void should_throwIllegalUse_when_idNotGiven() {
//when
final Throwable raisedException = catchThrowable(() -> getUserDAO.byId(null));
//then
assertThat(raisedException).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Id to fetch is mandatory");
}
Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.
Add this utility class:
import org.junit.Assert;
public abstract class ExpectedRuntimeExceptionAsserter {
private String expectedExceptionMessage;
public ExpectedRuntimeExceptionAsserter(String expectedExceptionMessage) {
this.expectedExceptionMessage = expectedExceptionMessage;
}
public final void run(){
try{
expectException();
Assert.fail(String.format("Expected a RuntimeException '%s'", expectedExceptionMessage));
} catch (RuntimeException e){
Assert.assertEquals("RuntimeException caught, but unexpected message", expectedExceptionMessage, e.getMessage());
}
}
protected abstract void expectException();
}
Then for my unit test, all I need is this code:
#Test
public void verifyAnonymousUserCantAccessPrivilegedResourceTest(){
new ExpectedRuntimeExceptionAsserter("anonymous user can't access privileged resource"){
#Override
protected void expectException() {
throw new RuntimeException("anonymous user can't access privileged resource");
}
}.run(); //passes test; expected exception is caught, and this #Test returns normally as "Passed"
}
If using #Rule, the exception set is applied to all the test methods in the Test class.
I would prefer AssertJ for this.
assertThatExceptionOfType(ExpectedException.class)
.isThrownBy(() -> {
// method call
}).withMessage("My message");
I like user64141's answer but found that it could be more generalized. Here's my take:
public abstract class ExpectedThrowableAsserter implements Runnable {
private final Class<? extends Throwable> throwableClass;
private final String expectedExceptionMessage;
protected ExpectedThrowableAsserter(Class<? extends Throwable> throwableClass, String expectedExceptionMessage) {
this.throwableClass = throwableClass;
this.expectedExceptionMessage = expectedExceptionMessage;
}
public final void run() {
try {
expectException();
} catch (Throwable e) {
assertTrue(String.format("Caught unexpected %s", e.getClass().getSimpleName()), throwableClass.isInstance(e));
assertEquals(String.format("%s caught, but unexpected message", throwableClass.getSimpleName()), expectedExceptionMessage, e.getMessage());
return;
}
fail(String.format("Expected %s, but no exception was thrown.", throwableClass.getSimpleName()));
}
protected abstract void expectException();
}
Note that leaving the "fail" statement within the try block causes the related assertion exception to be caught; using return within the catch statement prevents this.
Import the catch-exception library, and use that. It's much cleaner than the ExpectedException rule or a try-catch.
Example form their docs:
import static com.googlecode.catchexception.CatchException.*;
import static com.googlecode.catchexception.apis.CatchExceptionHamcrestMatchers.*;
// given: an empty list
List myList = new ArrayList();
// when: we try to get the first element of the list
catchException(myList).get(1);
// then: we expect an IndexOutOfBoundsException with message "Index: 1, Size: 0"
assertThat(caughtException(),
allOf(
instanceOf(IndexOutOfBoundsException.class),
hasMessage("Index: 1, Size: 0"),
hasNoCause()
)
);
#Test (expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "This is not allowed")
public void testInvalidValidation() throws Exception{
//test code
}