Skip to content

Commit

Permalink
Fixed tests using the new NUnit 4 scheme
Browse files Browse the repository at this point in the history
  • Loading branch information
omgitsjan authored and Jan Petry committed Feb 1, 2024
1 parent d564e59 commit ff03885
Show file tree
Hide file tree
Showing 6 changed files with 807 additions and 813 deletions.
188 changes: 94 additions & 94 deletions DiscordBotTests/ServiceTests/CryptoServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,98 +9,98 @@ namespace DiscordBotTests.ServiceTests;
[TestFixture]
public class CryptoServiceTests
{
private Mock<IHttpService> _mockHttpService = null!;
private CryptoService _cryptoService = null!;

[SetUp]
public void Setup()
{
_mockHttpService = new Mock<IHttpService>();

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string?>("ByBit:ApiUrl", "https://api.bybit.com/v2/public/tickers?symbol="),
});
var configuration = configurationBuilder.Build();

_cryptoService = new CryptoService(_mockHttpService.Object, configuration);
}

[Test]
public async Task GetCurrentCryptoPriceAsync_ReturnsCurrentPrice()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string jsonResponse = "{\"result\": [{\"last_price\": \"50000\"}]}";
const string expectedPrice = "50000";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(true, jsonResponse));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.IsTrue(success);
Assert.That(result, Is.EqualTo(expectedPrice));
}

[Test]
public async Task GetCurrentCryptoPriceAsync_ApiError_ReturnsErrorMessage()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string expectedErrorMessage = "API Error";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(false, expectedErrorMessage));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.IsFalse(success);
Assert.That(result, Is.EqualTo(expectedErrorMessage));
}

[Test]
public async Task GetCurrentCryptoPriceAsync_InvalidJson_ReturnsFallbackMessage()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string invalidJsonResponse = "Invalid JSON";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(true, invalidJsonResponse));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.IsFalse(success);
Assert.That(result, Is.EqualTo($"Could not fetch price of {symbol}..."));
}

[Test]
public async Task GetCurrentCryptoPriceAsync_MissingLastPrice_ReturnsFallbackMessage()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string jsonResponseMissingLastPrice = "{\"result\": [{}]}";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(true, jsonResponseMissingLastPrice));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.IsFalse(success);
Assert.That(result, Is.EqualTo($"Could not fetch price of {symbol}..."));
}
private Mock<IHttpService> _mockHttpService = null!;
private CryptoService _cryptoService = null!;

[SetUp]
public void Setup()
{
_mockHttpService = new Mock<IHttpService>();

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(new[]
{
new KeyValuePair<string, string?>("ByBit:ApiUrl", "https://api.bybit.com/v2/public/tickers?symbol="),
});
var configuration = configurationBuilder.Build();

_cryptoService = new CryptoService(_mockHttpService.Object, configuration);
}

[Test]
public async Task GetCurrentCryptoPriceAsync_ReturnsCurrentPrice()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string jsonResponse = "{\"result\": [{\"last_price\": \"50000\"}]}";
const string expectedPrice = "50000";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(true, jsonResponse));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.That(success, Is.True);
Assert.That(result, Is.EqualTo(expectedPrice));
}

[Test]
public async Task GetCurrentCryptoPriceAsync_ApiError_ReturnsErrorMessage()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string expectedErrorMessage = "API Error";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(false, expectedErrorMessage));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.That(success, Is.False);
Assert.That(result, Is.EqualTo(expectedErrorMessage));
}

[Test]
public async Task GetCurrentCryptoPriceAsync_InvalidJson_ReturnsFallbackMessage()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string invalidJsonResponse = "Invalid JSON";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(true, invalidJsonResponse));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.That(success, Is.False);
Assert.That(result, Is.EqualTo($"Could not fetch price of {symbol}..."));
}

[Test]
public async Task GetCurrentCryptoPriceAsync_MissingLastPrice_ReturnsFallbackMessage()
{
// Arrange
const string symbol = "BTC";
const string physicalCurrency = "USDT";
const string jsonResponseMissingLastPrice = "{\"result\": [{}]}";
_mockHttpService.Setup(x => x.GetResponseFromUrl(It.IsAny<string>(), It.IsAny<Method>(), It.IsAny<string>(),
It.IsAny<List<KeyValuePair<string, string>>>(), It.IsAny<object>()))
.ReturnsAsync(new HttpResponse(true, jsonResponseMissingLastPrice));

// Act
var (success, result) = await _cryptoService.GetCryptoPriceAsync(symbol, physicalCurrency);

// Assert
Assert.That(success, Is.False);
Assert.That(result, Is.EqualTo($"Could not fetch price of {symbol}..."));
}
}
194 changes: 96 additions & 98 deletions DiscordBotTests/ServiceTests/HttpServiceTests.cs
Original file line number Diff line number Diff line change
@@ -1,109 +1,107 @@
using System.Net;
using DiscordBot.Interfaces;
using DiscordBot.Services;
using Moq;
using Newtonsoft.Json;
using RestSharp;
using System.Net;

namespace DiscordBotTests.ServiceTests;

[TestFixture]
public class HttpServiceTests
{
[SetUp]
public void SetUp()
{
_mockRestClient = new Mock<IRestClient>();
_httpService = new HttpService(_mockRestClient.Object);
}

private Mock<IRestClient> _mockRestClient = null!;
private IHttpService _httpService = null!;

[Test]
public async Task GetResponseFromURL_WithValidResponse_ReturnsSuccess()
{
// Arrange
const string resource = "https://api.example.com/test";
const string content = "response content";
var response = new RestResponse
{ StatusCode = HttpStatusCode.OK, Content = content, IsSuccessStatusCode = true };
_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), default)).ReturnsAsync(response);

// Act
var result = await _httpService.GetResponseFromUrl(resource);

// Assert
Assert.IsTrue(result.IsSuccessStatusCode);
Assert.AreEqual(content, result.Content);
}

[Test]
public async Task GetResponseFromURL_WithErrorResponse_ReturnsError()
{
// Arrange
const string resource = "https://api.example.com/test";
const string errorMessage = "Error message";
var response = new RestResponse { StatusCode = HttpStatusCode.BadRequest, ErrorMessage = errorMessage };
_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), default)).ReturnsAsync(response);

// Act
var result = await _httpService.GetResponseFromUrl(resource, errorMessage: errorMessage);

// Assert
Assert.IsFalse(result.IsSuccessStatusCode);
Assert.AreEqual($"StatusCode: {response.StatusCode} | {errorMessage}", result.Content);
}

[Test]
public async Task GetResponseFromURL_WithHeaders_SendsHeaders()
{
// Arrange
const string resource = "https://api.example.com/test";
var headers = new List<KeyValuePair<string, string>>
{
new("Header1", "Value1"),
new("Header2", "Value2")
};
var response = new RestResponse { StatusCode = HttpStatusCode.OK, Content = "OK", IsSuccessStatusCode = true };

_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), default))
.Callback<RestRequest, CancellationToken>((req, token) =>
{
// Assert headers are set correctly within the Callback method.
foreach (var header in headers)
Assert.AreEqual(header.Value, req.Parameters.FirstOrDefault(p => p.Name == header.Key)?.Value);
})
.ReturnsAsync(response);

// Act
var result = await _httpService.GetResponseFromUrl(resource, headers: headers);

// Assert
Assert.IsTrue(result.IsSuccessStatusCode);
Assert.AreEqual(response.Content, result.Content);
}


[Test]
public async Task GetResponseFromURL_WithJsonBody_SendsJsonBody()
{
// Arrange
const string resource = "https://api.example.com/test";
var jsonBody = JsonConvert.SerializeObject(new { key = "value" });
var response = new RestResponse { StatusCode = HttpStatusCode.OK, IsSuccessStatusCode = true };
RestRequest? capturedRequest = null;
_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), It.IsAny<CancellationToken>()))
.Callback<RestRequest, CancellationToken>((r, _) => capturedRequest = r).ReturnsAsync(response);

// Act
await _httpService.GetResponseFromUrl(resource, jsonBody: jsonBody);

// Assert
Assert.IsNotNull(capturedRequest);
var requestBodyParameter = capturedRequest?.Parameters.FirstOrDefault(p =>
p.Type.Equals(ParameterType.RequestBody) && p.ContentType.Equals("application/json"));
Assert.IsNotNull(requestBodyParameter);
Assert.AreEqual(jsonBody, requestBodyParameter?.Value);
}
[SetUp]
public void SetUp()
{
_mockRestClient = new Mock<IRestClient>();
_httpService = new HttpService(_mockRestClient.Object);
}

private Mock<IRestClient> _mockRestClient = null!;
private HttpService _httpService = null!;

[Test]
public async Task GetResponseFromURL_WithValidResponse_ReturnsSuccess()
{
// Arrange
const string resource = "https://api.example.com/test";
const string content = "response content";
var response = new RestResponse
{ StatusCode = HttpStatusCode.OK, Content = content, IsSuccessStatusCode = true };
_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), default)).ReturnsAsync(response);

// Act
var result = await _httpService.GetResponseFromUrl(resource);

// Assert
Assert.That(result.IsSuccessStatusCode, Is.True);
Assert.That(content, Is.EqualTo(result.Content));
}

[Test]
public async Task GetResponseFromURL_WithErrorResponse_ReturnsError()
{
// Arrange
const string resource = "https://api.example.com/test";
const string errorMessage = "Error message";
var response = new RestResponse { StatusCode = HttpStatusCode.BadRequest, ErrorMessage = errorMessage };
_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), default)).ReturnsAsync(response);

// Act
var result = await _httpService.GetResponseFromUrl(resource, errorMessage: errorMessage);

// Assert
Assert.That(result.IsSuccessStatusCode, Is.False);
Assert.That($"StatusCode: {response.StatusCode} | {errorMessage}", Is.EqualTo(result.Content));
}

[Test]
public async Task GetResponseFromURL_WithHeaders_SendsHeaders()
{
// Arrange
const string resource = "https://api.example.com/test";
var headers = new List<KeyValuePair<string, string>>
{
new("Header1", "Value1"),
new("Header2", "Value2")
};
var response = new RestResponse { StatusCode = HttpStatusCode.OK, Content = "OK", IsSuccessStatusCode = true };

_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), default))
.Callback<RestRequest, CancellationToken>((req, _) =>
{
// Assert headers are set correctly within the Callback method.
foreach (var header in headers)
Assert.That(header.Value, Is.EqualTo(req.Parameters.FirstOrDefault(p => p.Name == header.Key)?.Value));
})
.ReturnsAsync(response);

// Act
var result = await _httpService.GetResponseFromUrl(resource, headers: headers);

// Assert
Assert.That(result.IsSuccessStatusCode, Is.True);
Assert.That(response.Content, Is.EqualTo(result.Content));
}

[Test]
public async Task GetResponseFromURL_WithJsonBody_SendsJsonBody()
{
// Arrange
const string resource = "https://api.example.com/test";
var jsonBody = JsonConvert.SerializeObject(new { key = "value" });
var response = new RestResponse { StatusCode = HttpStatusCode.OK, IsSuccessStatusCode = true };
RestRequest? capturedRequest = null;
_mockRestClient.Setup(client => client.ExecuteAsync(It.IsAny<RestRequest>(), It.IsAny<CancellationToken>()))
.Callback<RestRequest, CancellationToken>((r, _) => capturedRequest = r).ReturnsAsync(response);

// Act
await _httpService.GetResponseFromUrl(resource, jsonBody: jsonBody);

// Assert
Assert.That(capturedRequest, Is.Not.Null);
var requestBodyParameter = capturedRequest?.Parameters.FirstOrDefault(p =>
p.Type.Equals(ParameterType.RequestBody) && p.ContentType.Equals("application/json"));
Assert.That(requestBodyParameter, Is.Not.Null);
Assert.That(jsonBody, Is.EqualTo(requestBodyParameter?.Value));
}
}
Loading

0 comments on commit ff03885

Please sign in to comment.