Thursday, 11 February 2016

Applications: Security Configuration

By
This blog is in continuation of my previous blog Configuring Spring-Test-Mvc if you haven't read it please read it before this blog
  • Configure our custom authentication entry point, authentication
  • Create a custom configuration for the login filter bean. This configuration is required because     we want to use custom authentication success and failure handlers
  • Enable spring security by using the security namespace’s http element and set a reference to
  • Add a custom login filter to the Spring security namespace and ensure that this filter replaces

Authentication Tests
Login by Using Incorrect Credentials
    @Test
throws Exception {
{
Login by Using Incorrect Request Method
throws Exception {
{
Login by Using Correct Credentials
throws Exception {
{
Logout
Authorization Tests 
throws Exception {
{
added = TodoTestUtil.createDTO(null, "description",
"title"); 

A unit test is a piece of code written by a developer that executes a specific functionality in the code to be tested and asserts a certain behavior or state.
The percentage of code which is tested by unit tests is typically called test coverage.
A unit test targets a small unit of code, e.g., a method or a class, (local tests). External dependencies should be removed from unit tests, e.g., by replacing the dependency with a test implementation or a (mock) object created by a test framework.
An integration test has the target to test the behavior of a component or the integration between a set of components.
Integration tests check that the whole system works as intended, therefore they are reducing the need for intensive manual tests.
This kind of tests allow you to translate your user stories into a test suite, i.e., the test would resemble an expected user interaction with the application.
Performance tests are used to benchmark software components repeatedly. Their purpose is to ensure that the code under test runs fast enough even if it's under high load.
Typical unit tests are created in a separate project or separate source folder to keep the test code separate from the real code.


In any case you should write software tests for the critical and complex parts of your application. If you introduce new features a solid test suite also protects you against regression in existing code.
In general it is safe to ignore trivial code as, for example, getter and setter methods which simply assign values to fields. Writing tests for these statements is time consuming and pointless, as you would be testing the Java virtual machine. The JVM itself already has test cases for this and if you are developing end user applications you are safe to assume that a field assignment works in Java.
A JUnit test is a method contained in a class which is only used for testing. This is called a Test class.
To write a test with the JUnit 4.x framework you annotate a method with the @org.junit.Test annotation.
In this method you use an assert method, typically provided by the JUnit or another assert framework, to check the expected result of the code execution versus the actual result. These method calls are typically called asserts or assert statements.
You should provide meaningful messages in assert statements so that it is easier for the developer to identify the problem. This helps in fixing the issue, especially if someone looks at the problem, who did not write the code under test or the test code.
If you have several test classes, you can combine them into a test suite. Running a test suite will execute all test classes in that suite in the specified order.

JUnit annotations

Assert statements
JUnit provides static methods in the Assert class to test for certain conditions. These assert statements typically start withassert and allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.
JUnit assumes that all test methods can be executed in an arbitrary order. Well-written test code should not assume any order, i.e., tests should not depend on other tests.
You can use an annotation to define that the test methods are sorted by method name, in lexicographic order. To activate this feature, annotate your test class with the @FixMethodOrder(MethodSorters.NAME_ASCENDING) annotation.
      }
}

CalculateTest.java
Run As - Junit Test,
 if we change this line of code:
 so that the integers to be tested are not equal, the output will be:
And in the JUnit window, an error will appear and this message will be displayed:

@ExpectedDatabase("toDoData.xml")
    public void addEmptyTodo() throws Exception {
        mockMvc.perform(post("/todo/add")
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .sessionAttr("todo", new TodoDTO()))
        .andExpect(status().isOk())
        .andExpect(view().name("todo/add"))
        .andExpect(forwardedUrl("/WEB-INF/jsp/todo/add.jsp"))
       .andExpect(model().attributeHasFieldErrors("todo", "title"))
       .andExpect(model().attribute("todo",hasProperty("id",nullValue())))
       .andExpect(model().attribute("todo",                       
        hasProperty("description",isEmptyOrNullString())))
        .andExpect(model().attribute("todo", hasProperty("title",
        isEmptyOrNullString())));
    }

 @Test
    @ExpectedDatabase("toDoData.xml")
    public void addTodoWhenTitleAndDescriptionAreTooLong() throws Exception {
        String title = TodoTestUtil.createStringWithLength(101);
        String description = TodoTestUtil.createStringWithLength(501);

        mockMvc.perform(post("/todo/add")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("descryption", description)
                .param("title", title)
                .sessionAttr("todo", new TodoDTO())
        )
                .andExpect(status().isOk())
                .andExpect(view().name("todo/add"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/todo/add.jsp"))
                .andExpect(model().attributeHasFieldErrors("todo", "title"))
                .andExpect(model().attributeHasFieldErrors("todo","description"))
                .andExpect(model().attribute("todo",hasProperty("id",nullValue())))
                .andExpect(model().attribute("todo",hasProperty("description",is(                            description))))
                .andExpect(model().attribute("todo", hasProperty("title",
                           is(title))));
    }

@Test
    @ExpectedDatabase(value="toDoData-add-expected.xml", assertionMode = DatabaseAssertionMode.NON_STRICT)
    public void addTodo() throws Exception {
        mockMvc.perform(post("/todo/add")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("description", "description")
                .param("title", "title")
                .sessionAttr("todo", new TodoDTO())
        )
                .andExpect(status().isOk())
                .andExpect(view().name("redirect:/todo/view/{id}"))
                .andExpect(model().attribute("id", is("3")))
                .andExpect(flash().attribute("feedbackMessage", is("Todo entry:
                           title was added.")));
    }

@ExpectedDatabase("toDoData.xml")
    public void showUpdateTodoForm() throws Exception {
        mockMvc.perform(get("/todo/update/{id}", 1L))
                .andExpect(status().isOk())
                .andExpect(view().name("todo/update"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/todo/update.jsp"))
                .andExpect(model().attribute("todo", hasProperty("id", is(1L))))
                .andExpect(model().attribute("todo", hasProperty("description",
                           is("Lorem ipsum"))))
                .andExpect(model().attribute("todo", hasProperty("title",
                           is("Foo"))));
    }


 @Test
    @ExpectedDatabase("toDoData.xml")
    public void showUpdateTodoFormWhenTodoIsNotFound() throws Exception {
        mockMvc.perform(get("/todo/update/{id}", 3L))
                .andExpect(status().isNotFound())
                .andExpect(view().name("error/404"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/error/404.jsp"));
    }

@Test
    @ExpectedDatabase("toDoData.xml")
    public void showAddTodoForm() throws Exception {
        mockMvc.perform(get("/todo/add"))
                .andExpect(status().isOk())
                .andExpect(view().name("todo/add"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/todo/add.jsp"))
                .andExpect(model().attribute("todo",hasProperty("id", nullValue())))
                .andExpect(model().attribute("todo", hasProperty("description",
                           isEmptyOrNullString())))
                .andExpect(model().attribute("todo", hasProperty("title", isEmptyOrNullString())));
    }
}

@Test
    @ExpectedDatabase("toDoData.xml")
    public void findAll() throws Exception {
        mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("todo/list"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/todo/list.jsp"))
                .andExpect(model().attribute("todos", hasSize(2)))
                .andExpect(model().attribute("todos", hasItem(
                        allOf(
                                hasProperty("id", is(1L)),
                                hasProperty("description", is("Lorem ipsum")),
                                hasProperty("title", is("Foo"))
                        )
                )))
                .andExpect(model().attribute("todos", hasItem(
                        allOf(
                                hasProperty("id", is(2L)),
                                hasProperty("description", is("Lorem ipsum")),
                                hasProperty("title", is("Bar"))
                        )
                )));
    }
}

 @Test
    public void add_NewTodoEntry_ShouldAddTodoEntryAndRenderViewTodoEntryView() throws Exception {
        Todo added = new TodoBuilder()
                .id(1L)
                .description("description")
                .title("title")
                .build();
        when(todoServiceMock.add(isA(TodoDTO.class))).thenReturn(added);
        mockMvc.perform(post("/todo/add")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("description", "description")
                .param("title", "title")
                .sessionAttr("todo", new TodoDTO())
        )
                .andExpect(status().isMovedTemporarily())
                .andExpect(view().name("redirect:todo/{id}"))
                .andExpect(redirectedUrl("/todo/1"))
                .andExpect(model().attribute("id", is("1")))
                .andExpect(flash().attribute("feedbackMessage", is("Todo entry: title was added.")));
        ArgumentCaptor<TodoDTO> formObjectArgument = ArgumentCaptor.forClass(TodoDTO.class);
        verify(todoServiceMock, times(1)).add(formObjectArgument.capture());
        verifyNoMoreInteractions(todoServiceMock);
        TodoDTO formObject = formObjectArgument.getValue();
        assertThat(formObject.getDescription(), is("description"));
        assertNull(formObject.getId());
        assertThat(formObject.getTitle(), is("title"));
    }
}





0 comments :

Post a Comment