如何使用namedParameterJdbcTemplate为参数化查询编写DAO层的junit测试用例?

huangapple go评论59阅读模式
英文:

How to write junit test cases for DAO layer using namedParameterJdbcTemplate for parameterized query?

问题

To write test cases for the DAO layer using Mockito, you can follow these steps:

  1. Setup Mockito: Make sure you have Mockito set up in your test environment. You should have the necessary dependencies in your build configuration (e.g., Maven or Gradle).

  2. Create a Test Class: Create a test class for your GeneratorRepository DAO class. This class should be annotated with @RunWith(MockitoJUnitRunner.class) to initialize Mockito.

  3. Mock Dependencies: Mock the dependencies of your DAO class, such as NamedParameterJdbcTemplate and BeanPropertyRowMapper. You can use @Mock annotation to create mock objects.

  4. Inject Mocks: Inject the mocked dependencies into your GeneratorRepository class using the @InjectMocks annotation.

  5. Write Test Cases: Write test cases for the methods of your DAO class. In your test cases, you can use Mockito to define the behavior of the mocked dependencies when certain methods are called.

Here's an example of how you can write a test case for the findExistingUt method:

@RunWith(MockitoJUnitRunner.class)
public class GeneratorRepositoryTest {

    @Mock
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Mock
    private BeanPropertyRowMapper<Generator> generatorRowMapper;

    @InjectMocks
    private GeneratorRepository generatorRepo;

    @Test
    public void testFindExistingUt() {
        // Create a request
        Request request = new Request("12345", "F", 0, "XC");

        // Create an expected response
        Generator expectedResponse = new Generator("12345", "F", 0, "XC", "12345.FCST", "345TDGHDF45G", "OS01", null);

        // Define the behavior of the mock NamedParameterJdbcTemplate
        Mockito.when(namedParameterJdbcTemplate.queryForObject(
                ArgumentMatchers.eq(generatorRepo.getExistingUtQuery()), // Assuming you have a getter for existingUtQuery
                ArgumentMatchers.any(SqlParameterSource.class),
                ArgumentMatchers.eq(generatorRowMapper)
        )).thenReturn(expectedResponse);

        // Call the method under test
        Generator actualResponse = generatorRepo.findExistingUt(request);

        // Assert the result
        assertEquals(expectedResponse, actualResponse);
    }
}

In this example, we use Mockito.when to specify the behavior of the namedParameterJdbcTemplate mock when queryForObject is called. We then call the findExistingUt method and assert that the actual response matches the expected response.

Make sure to adapt the test case according to your actual class structure and requirements.

英文:

I have to write test cases for DAO layer and we use namedParameterJdbcTemplate.queryForObject to fetch details from database. We use BeanPropertyRowMapper and parameterrized queries.

DAO layer code as below

@Repository
public class GeneratorRepository {


	@Value(&quot;${sql.existingUtQuery}&quot;)
	private String existingUtQuery;

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Autowired
	private BeanPropertyRowMapper&lt;Generator&gt; generatorRowMapper;


	public generator findExistingUt(Request request) {
		Generator ut = new Generator();
		try {
			SqlParameterSource namedParameters = new MapSqlParameterSource()
					.addValue(&quot;no&quot;, request.getId(), Types.VARCHAR)
					.addValue(&quot;sub&quot;, request.getSub(), Types.VARCHAR)
					.addValue(&quot;rt&quot;, request.getRt(), Types.INTEGER)
					.addValue(&quot;sta&quot;, request.getSta(), Types.VARCHAR);
			ut = namedParameterJdbcTemplate.queryForObject(existingUtQuery, namedParameters, generatorRowMapper);
		} catch (EmptyResultDataAccessException e) {
			ut = null;
		} catch (Exception e) {
			throw e;
		}
		return ut;
	}

}

I am trying to write test cases as below

@Test
    public void findExistingUt() {
		Request request = new Request(&quot;12345&quot;, &quot;F&quot;, 0, &quot;XC&quot;);
		Generator expectedResponse = new Generator(&quot;12345&quot;, &quot;F&quot;, 0, &quot;XC&quot;,&quot;12345.FCST&quot;,&quot;345TDGHDF45G&quot;,&quot;OS01&quot;,null);
		String existingUtiQuery = &quot;select Top 1 * from existingUT where NO= :no AND SUB= :sub AND rt= :rt and STA= :sta order by LAST_UPDATE desc&quot;;
        Mockito.when(namedParameterJdbcTemplate.queryForObject(existingUtQuery, namedParameterJdbcTemplate, generatorRowMapper)).thenReturn(expectedResponse);
        Generator actualResponse = generatorRepo.findExistingUt(request);
        assertEquals(expectedResponse, actualResponse);
    }

How to write test cases for this DAO layer using Mockito ?

答案1

得分: 1

以下是翻译好的部分:

"InjectMocks on a class that you are testing." 翻译为 "在你正在测试的类上使用InjectMocks。"
"Mock dependencies." 翻译为 "模拟依赖项。"
"Set up environment variables." 翻译为 "设置环境变量。"
"and the in-test use argument matches." 翻译为 "在测试中使用参数匹配。"
"Hope it work." 翻译为 "希望它正常工作。"
"@RunWith(MockitoJUnitRunner.class)" 翻译为 "使用MockitoJUnitRunner.class运行。"
"@Mock" 翻译为 "模拟(Mock)"
"@InjectMocks" 翻译为 "注入模拟(InjectMocks)"
"@Before" 翻译为 "在测试之前"
"@Test" 翻译为 "测试"
"public void testFindExistingUt()" 翻译为 "测试findExistingUt方法"
"Request request = new Request("12345", "F", 0, "XC");" 翻译为 "请求request = new Request('12345', 'F', 0, 'XC');"
"Generator expectedResponse = new Generator("12345", "F", 0, "XC", "12345.FCST", "345TDGHDF45G", "OS01", null);" 翻译为 "期望的响应expectedResponse = new Generator('12345', 'F', 0, 'XC', '12345.FCST', '345TDGHDF45G', 'OS01', null);"
"Mockito.when(namedParameterJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(SqlParameterSource.class), Mockito.any(BeanPropertyRowMapper.class)))" 翻译为 "当(namedParameterJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(SqlParameterSource.class), Mockito.any(BeanPropertyRowMapper.class)))时"
".thenReturn(expectedResponse);" 翻译为 ".thenReturn(expectedResponse);"
"Generator actualResponse = generatorRepository.findExistingUt(request);" 翻译为 "实际响应actualResponse = generatorRepository.findExistingUt(request);"
"assertEquals(expectedResponse, actualResponse);" 翻译为 "assertEquals(expectedResponse, actualResponse);"
"Mockito.verify(namedParameterJdbcTemplate).queryForObject(Mockito.anyString(), Mockito.any(SqlParameterSource.class), Mockito.any(BeanPropertyRowMapper.class));" 翻译为 "Mockito.verify(namedParameterJdbcTemplate).queryForObject(Mockito.anyString(), Mockito.any(SqlParameterSource.class), Mockito.any(BeanPropertyRowMapper.class));"

英文:

The code is not reproducible. So it should look this way. InjectMocks on a class that you are testing. Mock dependencies. Set up environment variables. and the in-test use argument matches. Hope it work.

@RunWith(MockitoJUnitRunner.class)
public class GeneratorRepositoryTest {

    @Mock
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @InjectMocks
    private GeneratorRepository generatorRepository;
    
    @Before
    public void setUp() {
        ReflectionTestUtils.setField(generatorRepository, &quot;existingUtQuery&quot;, &quot;select Top 1 * from existingUT where NO= :no AND SUB= :sub AND rt= :rt and STA= :sta order by LAST_UPDATE desc&quot;);
    }

   @Test
    public void testFindExistingUt() {
    Request request = new Request(&quot;12345&quot;, &quot;F&quot;, 0, &quot;XC&quot;);
    Generator expectedResponse = new Generator(&quot;12345&quot;, &quot;F&quot;, 0, &quot;XC&quot;, &quot;12345.FCST&quot;, &quot;345TDGHDF45G&quot;, &quot;OS01&quot;, null);

    Mockito.when(namedParameterJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(SqlParameterSource.class), Mockito.any(BeanPropertyRowMapper.class)))
            .thenReturn(expectedResponse);

    Generator actualResponse = generatorRepository.findExistingUt(request);

    assertEquals(expectedResponse, actualResponse);
    Mockito.verify(namedParameterJdbcTemplate).queryForObject(Mockito.anyString(), Mockito.any(SqlParameterSource.class), Mockito.any(BeanPropertyRowMapper.class));
}

}

huangapple
  • 本文由 发表于 2023年5月10日 13:30:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215167.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定