2022-07-01

Tests for Spring Controllers with session attributes

Diffblue Cover now writes tests for Spring Controllers with session attributes, for both the CLI and the IntelliJ plugin. For example:


@ContextConfiguration(classes = {MyController.class})

@ExtendWith(SpringExtension.class)

class MyControllerDiffblueTest {
  @Autowired
  private MyController myController;

  @MockBean
  private Plain plain;
  /**
   * Method under test: {@link MyController#doSomethingOnBeanField(List)}
   */
  @Test
  void testDoSomethingOnBeanField() throws Exception {
    // Arrange
    when(plain.doSomething()).thenReturn("Do Something");
    MockHttpServletRequestBuilder getResult = MockMvcRequestBuilders.get("/do-plain");
    MockHttpServletRequestBuilder requestBuilder = getResult.sessionAttr("bandersnatch", new ArrayList<>());

    // Act and Assert
    MockMvcBuilders.standaloneSetup(myController)
        .build()
        .perform(requestBuilder)
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType("text/plain;charset=ISO-8859-1"))
        .andExpect(MockMvcResultMatchers.content().string("Do Something"));
  }

Tests for classes implementing the Builder pattern

Diffblue Cover now recognises that build is a builder method, i.e. it creates a new object using the fields of the class to call a constructor and returns the result. This means that we can now write tests by calling the build method and asserting on its result.

Coming soon!

We are busy getting ready for IntelliJ 2022.2! More details when the new IntelliJ release is announced, please watch this space.

Developer Edition trial available

How do I automatically maintain all of these tests?

Enhancements

  • CLI: Cover now detects testable methods faster. [Ref: TG-17337]

  • Cover now always includes MethodGroup failure reasons, if present, in the log file. [Ref: TG-17121]

  • Cover now provides improved guidance when an R012 (JNI sandbox policy violation) has been encountered. [Ref: TG-17100]

  • Cover now sets @SessionAttributes for Spring Controller tests when appropriate. [Ref: TG-17070]

  • Cover is now able to write tests for classes implementing the Builder pattern. [Ref: TG-13577]

Resolved Issues

  • CLI: Resolved an issue which caused Cover to reject prefixes which end in a Java keyword. [Ref: TG-17358]

Known Issues

  • CLI: The command dcover clean --failing does not work on Gradle projects. This command is now deprecated and dcover validate should be used instead. [Ref: TG-11707]

  • For multi-module projects, --coverage-reports needs to be run in the sub-modules, not from root module with --working-directory. [Ref: TG-16876]

Last updated

Was this helpful?