Sonarqube LinesTo Cover C#(测试)
Posted
技术标签:
【中文标题】Sonarqube LinesTo Cover C#(测试)【英文标题】:Sonarqube LinesTo Cover C# (test) 【发布时间】:2021-11-23 23:54:41 【问题描述】:我正在使用 Sonarqube 和 sonarqube-8.5.1.38104
这是我的一般结果
1. KeyValueByClientAndCampaignAsync
sn-p 代码
代码:
/// <summary>
/// Metodo encargado de consultar los registros en formato de diccionario
/// </summary>
/// <param name="idClient">Id de cliente a consultar</param>
/// <param name="idCampaign">Id de campaña a consultar</param>
/// <returns>System.Threading.Tasks.Task que representa la operación asincrónica, con la información de los registros</returns>
public async Task<Dictionary<decimal, string>> KeyValueByClientAndCampaignAsync(decimal idClient, decimal idCampaign)
// Consultamos la memoria a partir del estado
var data = await this.memory.KeyValueAsync<AttachmentDto, decimal, string>(x => x.IdClient, idClient, x => x.Id, x => x.Name, x => x.IdClient == idClient && x.IdCampaign == idCampaign && x.State);
// Validamos si se enontraron registros
if (!data.Any())
// Consultamos la base transaccional
data = await this.repository.Search<Entities.Attachment>(x => x.IdClient == idClient && x.IdCampaign == idCampaign && x.State).ToDictionaryAsync(x => x.Id, x => x.Name);
// Retornamos la información
return data;
测试 sn-p 代码:
/// <summary>
/// Valida que se obtenga la información de la cache y que se retorne los mismos registros
/// </summary>
[Fact]
public async Task KeyValueByClientAndCampaignAsync_Overloaded_Memory_ReturnSameEntities()
var isInvokedKeyValueMemory = false;
// Arrange
var memoryJson = base.GetMemory(x =>
x.Setup(o => o.KeyValueAsync(It.IsAny<Expression<Func<AttachmentDto, object>>>(), It.IsAny<object>(), It.IsAny<Func<AttachmentDto, decimal>>(), It.IsAny<Func<AttachmentDto, string>>(), It.IsAny<Expression<Func<AttachmentDto, bool>>>()))
.ReturnsAsync(AttachmentFake.KeyValueEntities)
.Callback(() => isInvokedKeyValueMemory = true);
);
var logic = new AttachmentLogic(base.GetRepository<IAttachmentRepository>(),
base.mapper,
memoryJson);
// Act
var dictionary = await logic.KeyValueByClientAndCampaignAsync(1, 1);
// Assert
Assert.NotEmpty(dictionary);
Assert.Equal(AttachmentFake.KeyValueEntities, dictionary);
Assert.True(isInvokedKeyValueMemory);
/// <summary>
/// Valida que se obtenga la información de los repositorios y que se retorne los mismos registros
/// </summary>
[Fact]
public Task KeyValueByClientAndCampaignAsync_Overloaded_Repository_ReturnSameEntities() => base.ProcessInMemory<IAttachmentRepository>(async (repository, context) =>
// Arrange
await repository.CreateRangeAsync(AttachmentFake.Attachments);
var memoryJson = base.GetMemory(x =>
x.Setup(o => o.KeyValueAsync(It.IsAny<Expression<Func<AttachmentDto, object>>>(), It.IsAny<object>(), It.IsAny<Func<AttachmentDto, decimal>>(), It.IsAny<Func<AttachmentDto, string>>(), It.IsAny<Expression<Func<AttachmentDto, bool>>>()))
.ReturnsAsync(new Dictionary<decimal, string>());
);
var logic = new AttachmentLogic(repository,
base.mapper,
memoryJson);
// Act
var result = await logic.KeyValueByClientAndCampaignAsync(1, 1);
// Assert
Assert.NotEmpty(result);
Assert.Equal(AttachmentFake.KeyValueEntitiesTrue, result);
);
2. GetByClientAndCampaignAsync
sn-p 代码
代码:
/// <summary>
/// Metodo encargado de consultar los registros por cliente, campaña y tipo de plantilla
/// </summary>
/// <param name="idClient">Id de cliente a consultar</param>
/// <param name="idCampaign">Id de campaña a consultar</param>
/// <exception cref="ArgumentException">Se genera cuando el id especificado no es valido.</exception>
/// <returns>System.Threading.Tasks.Task que representa la operación asincrónica, con la información del registro especificado</returns>
public async Task<List<AttachmentDto>> GetByClientAndCampaignAsync(decimal idClient, decimal idCampaign)
// Buscamos el listado de plantillas en la cache
var entities = await this.memory.FindAllAsync<AttachmentDto>(x => x.IdClient, idClient, x => x.IdClient == idClient && x.IdCampaign == idCampaign);
// Validamos si se encontraron registros
if (!entities.Any())
// Buscamos los registros en la base transaccional
var result = await this.repository.Search<Entities.Attachment>(x => x.IdClient == idClient && x.IdCampaign == idCampaign).ToListAsync();
// Convertimos la información
entities = this.mapper.Map<List<AttachmentDto>>(result);
// Retornamos la información
return entities;
测试 sn-p 代码:
/// <summary>
/// Valida que se obtenga la información de la caché y que se retorne los mismos registros
/// </summary>
[Theory]
[MemberData(nameof(AttachmentFake.ListAttachmentsCustom), MemberType = typeof(AttachmentFake))]
public Task GetByClientAndCampaignAsync_Memory_ReturnSameEntities(decimal idClient, decimal idCampaign, List<Entities.Attachment> data) => base.ProcessInMemory<IAttachmentRepository>(async (repository, context) =>
// Arrange
await repository.CreateRangeAsync(data);
var memoryJson = base.GetMemory(o =>
o.Setup(x => x.FindAllAsync(
It.IsAny<Expression<Func<AttachmentDto, object>>>(),
It.IsAny<object>(),
It.IsAny<Expression<Func<AttachmentDto, bool>>>()
))
.ReturnsAsync(base.mapper.Map<List<AttachmentDto>>(data));
);
var logic = new AttachmentLogic(repository,
base.mapper,
memoryJson);
// Act
var result = await logic.GetByClientAndCampaignAsync(idClient, idCampaign);
// Assert
Assert.Equal(data.Count, result.Count);
);
/// <summary>
/// Valida que se obtenga la información de los repositorios y que se retorne los mismos registros
/// </summary>
[Theory]
[MemberData(nameof(AttachmentFake.ListAttachmentsCustom), MemberType = typeof(AttachmentFake))]
public Task GetByClientAndCampaignAsync_Repository_ReturnSameEntities(decimal idClient, decimal idCampaign, List<Entities.Attachment> data) => base.ProcessInMemory<IAttachmentRepository>(async (repository, context) =>
// Arrange
await repository.CreateRangeAsync(data);
var memoryJson = base.GetMemory(o =>
o.Setup(x => x.FindAllAsync(
It.IsAny<Expression<Func<AttachmentDto, object>>>(),
It.IsAny<object>(),
It.IsAny<Expression<Func<AttachmentDto, bool>>>()
))
.ReturnsAsync(new List<AttachmentDto>());
);
var logic = new AttachmentLogic(repository,
base.mapper,
memoryJson);
// Act
var result = await logic.GetByClientAndCampaignAsync(idClient, idCampaign);
// Assert
Assert.Equal(data.Count, result.Count);
);
3. PaginationByClientAndCampaignAsync
sn-p 代码
代码:
/// <summary>
/// Metodo encargado de consultar los registros paginando desde la base de datos
/// </summary>
/// <param name="idClient">Id de cliente a consultar</param>
/// <param name="idCampaign">Id de campaña a consultar</param>
/// <param name="paging">Parametros de la paginación</param>
/// <returns>System.Threading.Tasks.Task que representa la operación asincrónica, con la información de los registros</returns>
public async Task<PagedResult<AttachmentDto>> PaginationByClientAndCampaignAsync(decimal idClient, decimal idCampaign, PagingParameter paging)
// Consultamos la información en la transaccional
var result = await this.repository
.Search<Entities.Attachment>(x => x.IdClient == idClient && x.IdCampaign == idCampaign)
.GetPagedAsync(paging.PageNumber, paging.PageSize);
// Convertimos la información
var data = this.mapper.Map<PagedResult<AttachmentDto>>(result);
// Retornamos la información
return data;
测试 sn-p 代码:
/// <summary>
/// Valida que se obtenga la información de los repositorios y que se retorne los mismos registros
/// </summary>
[Fact]
public Task PaginationByClientAndCampaignAsync_Repository_ReturnSameEntities() => base.ProcessInMemory<IAttachmentRepository>(async (repository, context) =>
// Arrange
var entities = AttachmentFake.AttachmentsPagination;
var parameter = new PagingParameter()
PageNumber = 1,
PageSize = 10
;
var data = new PagedResult<Entities.Attachment>()
CurrentPage = 1,
PageCount = 1,
PageSize = 10,
Results = entities,
RowCount = entities.Count
;
await repository.CreateRangeAsync(AttachmentFake.AttachmentsPagination);
var logic = new AttachmentLogic(repository,
base.mapper,
base.GetMemory());
// Act
var result = await logic.PaginationByClientAndCampaignAsync(1, 1, parameter);
// Assert
Assert.NotNull(result);
Assert.Equal(data.FirstRowOnPage, result.FirstRowOnPage);
Assert.Equal(data.LastRowOnPage, result.LastRowOnPage);
Assert.Equal(data.PageCount, result.PageCount);
Assert.Equal(data.PageSize, result.PageSize);
Assert.Equal(data.Results.Count, result.Results.Count);
Assert.Equal(data.RowCount, result.RowCount);
);
如您所见,三个 sn-ps 代码(及其测试)非常相似。
我试图解决这些问题,但我仍然遇到问题,因为我的管道由于质量门(我无法控制)而没有通过。
如果你能给我一个线索,为了解决那个测试,我将非常感激。
您将如何构建这些测试?
你会对他们做哪些改变?
非常感谢。
【问题讨论】:
【参考方案1】:对于 .NET 项目,必须在构建期间生成测试结果报告。结果为 XML 格式,必须存储在 SonarQube 将读取它并将其包含在其报告中的某个位置。
Maybe this official documentation will help.
运行单元测试并将结果保存在文件“NUnitResults.xml”中
packages\NUnit.ConsoleRunner.3.7.0\tools\nunit3-console.exe --result=NUnitResults.xml "NUnitTestProject1\bin\Debug\NUnitTestProject1.dll"
导入单元测试结果
要导入测试执行报告,在开始步骤中,您需要传递一个指向将要生成的文件的参数:
sonar.cs.nunit.reportsPaths
用于 NUnit
完整的命令类似于:
dotnet sonarscanner begin /k:PROJECT_NAME /d:sonar.login=LOGIN_TOKEN /d:sonar.host.url=URL /d:sonar.cs.nunit.reportsPath=PATH_TO_NUnitResults.xml
【讨论】:
以上是关于Sonarqube LinesTo Cover C#(测试)的主要内容,如果未能解决你的问题,请参考以下文章