Spring Boot passes test case that should fail - java

I have added a test case in my Spring Boot application. However, when I ./gradlew build, all the test cases pass. Any reason?
#Test
public void testIntentionalError() throws Exception {
boolean thrown = true;
assertThat(!thrown);
}

It's because your test doesn't test anything.
Try this :
#Test
public void testIntentionalError() throws Exception {
boolean thrown = true;
assertTrue(!thrown);
}

you can try something like the following (in case you want to use the assertThat method):
#Test
public void testIntentionalError() throws Exception {
boolean thrown = true;
assertThat(!thrown, is(true));
}
using hamcrest matcher (import static org.hamcrest.core.Is.is)

Related

Mockito testing a function that throws log error

I am new to writing test cases.
I need to test a part of a function that does not return anything.
It should be able to validate containsHello is true
or
check if a log error is obtained or not
public void Myfunction(x){
Boolean containsHello;
if (x != null) {
if ((x.contains(“hello"))
{
containsHello = true;
if (AppConfig.isWord()
&& (Secondclass.isSentence() && containsHello)) {
log.error("");
}
}
}
More code
}
Secondclass is a final class defined outside of the current .java file
AppConfig is also a class that exists outside the java file being tested.
How to run a test for the above code using Mockito. I tried the below code But does not work:
#Test
public void TestingmyFunction() throws Exception {
String x=“hello"
Mockito.when(Secondclass.isSentence()).thenReturn(true);
Mockito.when(AppConfig.isWord()).thenReturn(true);
Myfunction(x);
}
But I am not able to access the AppConfig.isWord() or Secondclass.isSentence()
Tried with powerMockito which throws this error:
java.lang.IllegalStateException: Failed to transform class with name com.amazon.alfred.cli.action.DeployBundleTests. Reason: javassist.bytecode.InterfaceMethodrefInfo cannot be cast to javassist.bytecode.MethodrefInfo
#Test
public void TestingmyFunction() throws Exception {
String x=“hello"
PowerMockito.mockStatic(Secondclass.class)
PowerMockito.when(Secondclass.isSentence()).thenReturn(true);
PowerMockito.mockStatic(AppConfig.class);
PowerMockito.when(AppConfig.isWord()).thenReturn(true);
Myfunction(x);
}

Performing assertion after exception using EasyMock

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.

Null Pointer Exception in JUnit test case

Is there any way to write a mockito test case for the particular case.
public void saveStaffInfo(HttpServletResponse response, RegBean regdata, Staffinfo staffType, boolean status)
throws IOException {
if (status)
{
boolean status1 = staffType.insertlogin(regdata);
if(status1) {
response.sendRedirect("registration.jsp?status=success");
}
else {
response.sendRedirect("registration.jsp?status=login_table_error");
}
} else {
response.sendRedirect("registration.jsp?status=failed");
}
}
I did mock the HttpServeletResponse, RegBean,Staffinfo. However, as it is of void type so I cannot use doReturn().when(mockedMethod).(someMethod). So how do I test these lines?
I also need code coverage. I am very new to this.
The test case
#Test
public void testSaveStaffInfo() throws IOException, ServletException{
boolean status =true;
// System.out.println(iStaffInfo.insertlogin(regdata));
Mockito.when(iStaffInfo.insertlogin(regdata)).thenReturn(Boolean.TRUE );
reg.saveStaffInfo(response, regdata, iStaffInfo,status);
}
You need to think what it is you want to test here. What is the "output"? The "output" here is that the method is doing something to your HttpServletResponse, it is calling sendRedirect.
You can verify that certain methods are being called on your mocked (or real) objects with Mockito.verify

Using junit #Rule, expectMessage(), matcher for multipe exception in 1 tested method [duplicate]

This question already has answers here:
How to continue test after JUnit ExpectedException if thrown?
(4 answers)
Closed 6 years ago.
In my Android project I want to test, with the same #Test, a class which can throw several times the same exception with different messages.
I want my test to pass for a given list of messages and to fail for others.
Making some research on Junit I tried to implement this using #Rule, expectMessage() and Hamcrest matcher.
My implementation is currently based on the "Custom matcher" described here.
#RunWith(AndroidJUnit4.class)
public class TestException extends ApplicationTestCase {
#Rule public ExpectedException thrown= ExpectedException.none();
public TestException(){
super(AplicatyApplication.class);
}
#Test
public void testException() throws Exception {
thrown.expect(IndexOutOfBoundsException.class);
thrown.expectMessage(new MatchesPattern("*"));
Dummy.exec(0);
// do more stuff here ...
Dummy.exec(1);
// ...
Dummy.exec(2);
// ...
Dummy.exec(3); // I want my test to fail here
// ...
}
class MatchesPattern extends TypeSafeMatcher<String> {
private String pattern;
public MatchesPattern(String pattern) {
this.pattern = pattern;
}
#Override
protected boolean matchesSafely(String item) {
return item.matches(pattern)
&&
item.startsWith("My message")
&& (
item.endsWith("1")
||
item.endsWith("2")
);
}
#Override
public void describeTo(Description description) {
description.appendText("matches pattern ").appendValue(pattern);
}
#Override
protected void describeMismatchSafely(String item, Description mismatchDescription) {
mismatchDescription.appendText("does not match");
}
}
static class Dummy {
static void exec(int i){
if(i == 0)
return;
if(i == 1)
throw new IndexOutOfBoundsException("My message1");
if(i == 2)
throw new IndexOutOfBoundsException("My message2");
if(i == 3)
throw new IndexOutOfBoundsException("My message3");
}
}
}
Running this test I can see that the matcher is called just once, executing Dummy.exec(1);.
The matchesSafely(String item) returns true and the the test ends with the status Passed.
All this seems to be Okay, with my understanding of the #Rule. I was waiting an exception : I got it; I was waiting a given message : I got it.
I can not find a way to continue the execution of my test once the first exception has been thrown.
My questions are :
Is it possible to use #Rule to check more than one exception thrown into one tested method, or do I have to use the typical try/catch testing the exception message in every catch block?.
Is there another/more elegant way to test this type of concerns.
I suggest to split the test method into multiple tests, one for each requirement.
#Test
public void testException_1() throws Exception {
thrown.expect(IndexOutOfBoundsException.class);
thrown.expectMessage("My message1");
Dummy.exec(1);
}
In case it needs to be in one test method, I would build it with try-catch and ErrorCollector.
#Test
public void testException_1() throws Exception {
try {
Dummy.exec(1);
fail();
} catch (IndexOutOfBoundsException e) {
errorCollector.checkThat(e.getMessage(), is("My message1"));
}
try {
Dummy.exec(2);
...
} ...
}
I would try to avoid to build a custom Matcher.

How to check multiple exceptions with one JUnit Method?

i have this code in my program which is needed to be tested with jUnit
void deleteCustomer(String name) throws UnknownCustomerException,
AccountNotEmptyException {
if (name == null) {
throw new NullPointerException();
} else if (!exists(name)) {
throw new UnknownCustomerException();
} else if (getCustomer(name).deletable()) {
customerList.remove(getCustomer(name));
}
}
I thought i can test it in one JUnit method like
#Test
public void createCustomer(){
System.out.println("createCustomerTest");
try {
element.createCustomer(null);
//fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (NullPointerException anIndexOutOfBoundsException) {
assertTrue(anIndexOutOfBoundsException.getMessage().equals("NullPointerException"));
}
}
As you can see I already tried unsuccessfully to implement the NPE.
How can I check for several Exceptions in one JUnit Method? I checked some How-To's in the web but failed with that too.
I think in your case you should have separate tests, however you can achieve this like so if using Java 8:
Using an AssertJ 3 assertion, which can be used alongside JUnit:
import static org.assertj.core.api.Assertions.*;
#Test
public void test() {
Element element = new Element();
assertThatThrownBy(() -> element.createCustomer(null))
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("NullPointerException");
assertThatThrownBy(() -> element.get(1))
.isInstanceOf(IndexOutOfBoundsException.class);
}
It's better than #Test(expected=IndexOutOfBoundsException.class) or .expect syntax because it guarantees the expected line in the test threw the exception and lets you check more details about the exception, such as message.
Maven/Gradle instructions here.
Write for each exception its own test. It will be only one thrown at a time anyway.
For example a simplified method:
void deleteCustomer( String name ) throws UnknownCustomerException
{
if ( name == null )
{
throw new NullPointerException();
}
else if ( !exists( name ) )
{
throw new UnknownCustomerException();
}
}
You have then two tests that each check if its exception is thrown:
#Test( expected = NullPointerException.class )
public void deleteCustomer_shouldThrowNullpointerIfNameIsNull() throws UnknownCustomerException
{
String name = null;
cut.deleteCustomer( name );
}
#Test( expected = UnknownCustomerException.class )
public void deleteCustomer_shouldThrowUnknownCustomerExceptionIfNameIsUnknown() throws UnknownCustomerException
{
String name = "someUnknownName";
cut.deleteCustomer( name );
}
The problem with the NullpointerException is, that the test is true/successful/green if the NPE is thrown anywhere in the method - so you should make sure, that that is not happening for the test to be meaningful.
You could add several "catch" statement into the test method for different exceptions, like:
try {
element.createCustomer(null);
Assert.fail("Exception was expected!");
} catch (NullPointerException _ignore) {
} catch (UnknownCustomerException _ignore) {
}
or with Java 87
try {
element.createCustomer(null);
Assert.fail("Exception was expected!");
} catch (NullPointerException | UnknownCustomerException _ignore) {
}
But if you switch from JUnit to TestNG, then your test will be much cleaner:
#org.testng.annotations.Test(expectedExceptions = { NullPointerException.class, UnknownCustomerException.class })
public void createCustomer() throws NullPointerException, UnknownCustomerException {
element.createCustomer(null);
}
More information about "expectedException" is here: http://testng.org/doc/documentation-main.html and example of the usage can be found here: http://www.mkyong.com/unittest/testng-tutorial-2-expected-exception-test/
I suggest that you take a closer look at the JavaDoc of ExpectedException and implement different tests for different validations, e.g.
public class CustomerTest {
#Rule
public ExpectedException exception = ExpectedException.none();
#Test
public void throwsNullPointerExceptionForNullArg() {
exception.expect(NullPointerException.class);
element.createCustomer(null);
}
#Test
public void throwsUnknwonCustomerExceptionForUnkownCustomer() {
exception.expect(UnknownCustomerException.class);
// exception.expectMessage("Some exception message"); uncomment to verify exception message
element.createCustomer("unknownCustomerName");
}
#Test
public void doesNotThrowExceptionForKnownCustomer() {
element.createCustomer("a known customer");
// this test pass since ExpectedException.none() defaults to no exception
}
}

Categories

Resources